Search code examples
javascriptgoogle-mapsgoogle-street-view

Map onClick Handler Fails - InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number


I have a simple page with GMap and Streetview div's. While an external link sets a new location OK in both div's, trying to do so in the map click handler fails. (I suspect there may be some closure rule I'm missing.) Script is as follows:

var map, panorama;

function do_show ( a, b ) {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: a, lng: b}, zoom: 14
        });

    map.addListener ( 'click', function(e) {

        do_show ( e.latLng.lat().toFixed(6), e.latLng.lng().toFixed(6) );
        } );        // end addListener()                    

    panorama = new google.maps.StreetViewPanorama(
            document.getElementById('pano'), {
                position: {lat: a, lng: b},
                pov: { heading: 34, pitch: 10 }
                });
    map.setStreetView(panorama);
}       // end function do_show()

function pre_init () {
    panorama = map = null;
    do_show( 42.345573,  -71.098326 );      // Boston
    }
</script>
<script async defer
        src="https://maps.googleapis.com/maps/api/js?key=YOUR_KEY&callback=pre_init">
</script>

Solution

  • I get the self-explanatory error in the javascript console: InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number (they are strings, not numbers). Remove the .toFixed(6) from them.

    map.addListener ( 'click', function(e) {
    
       do_show ( e.latLng.lat(), e.latLng.lng() );
    });        // end addListener()                    
    

    proof of concept fiddle

    code snippet:

    html,
    body,
    #map,
    #pano {
      height: 100%;
      margin: 0px;
      padding: 0px
    }
    
    #map {
      width: 50%;
      float: right;
    }
    
    #pano {
      width: 50%;
    }
    <script>
      var map, panorama;
    
      function do_show(a, b) {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {
            lat: a,
            lng: b
          },
          zoom: 14
        });
    
        map.addListener('click', function(e) {
    
          do_show(e.latLng.lat(), e.latLng.lng());
        }); // end addListener()                    
    
        panorama = new google.maps.StreetViewPanorama(
          document.getElementById('pano'), {
            position: {
              lat: a,
              lng: b
            },
            pov: {
              heading: 34,
              pitch: 10
            }
          });
        map.setStreetView(panorama);
      } // end function do_show()
    
      function pre_init() {
        panorama = map = null;
        do_show(42.345573, -71.098326); // Boston
      }
    </script>
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=pre_init">
    </script>
    <div id="map"></div>
    <div id="pano"></div>