[GIS] How to set Google Maps pegman position programmatically

google mapsgoogle-street-viewhtmljavascript

I've this sample code that use Google Maps anb Google Street View ….

<html>
  <head>
    <meta charset="utf-8">
    <title>Set Pegman position programmatically</title>

    <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }

      #google_map, #google_streetview {
        float: left;
        height: 50%;
        width: 50%;
      }
    </style>
  </head>
  <body>
    <!-- ### The page structure ... -->
    <div id="the_form">

      <form id="form" onsubmit="return false;">
          Lat: <input id="lat" type="text" />
          Lon: <input id="lon" type="text" />
          <input type="submit" onclick="getLatLon();" />
      </form>

      <script>
        function getlatLon() {
            var lat = document.getElementById("lat").value;
            var lon = document.getElementById("lon").value;
        }
      </script>
    </div>
    <div id="google_map"></div>
    <div id="google_streetview"></div>

    <script>
      function initialize() {
        //### The original pegman position ...
        var pegman_position = {lat: 42.345573, lng: -71.098326};
        var marker;


        //### Add Google Map ...
        var google_map = new google.maps.Map(document.getElementById('google_map'), {
          center: pegman_position,
          zoom: 14
        });

        //### Add Google Street View ...
        var panorama = new google.maps.StreetViewPanorama(
            document.getElementById('google_streetview'), {
              position: pegman_position,
              pov: {
                heading: 34,
                pitch: 10
              }
            });
        google_map.setStreetView(panorama);

        panorama.addListener('position_changed', function(){
            var latLon = { lat: panorama.getPosition().lat(), lng: panorama.getPosition().lng() };
        });
      }
    </script>
    <script async defer
        src="https://maps.googleapis.com/maps/api/js?key=<PUT_YOUR_API_KEY_HERE>&callback=initialize">
    </script>
  </body>
</html>

(NOTE: if you'd like to execute it you've to put you Google API Key at the bottom of the code ….)

I'd like to slightly modify the lat / lon coordinates values in the two specific input values (this code is a simulation of my real needs … ), and to see that the pegman moves on the Google Map and the Stret View image udpate itself.

Suggetions / examples?

Best Answer

Here you go. https://jsfiddle.net/35rpw0jv/

And this is how you center the Pegman (and the map) upon every street view move (position change).

panorama.addListener('position_changed', function(){
            map.setCenter(panorama.getPosition());
    });