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

江枫思渺然 提交于 2019-12-25 17:38:26

问题


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>

回答1:


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>


来源:https://stackoverflow.com/questions/44604786/map-onclick-handler-fails-invalidvalueerror-setcenter-not-a-latlng-or-latlng

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!