首页 文章

中心谷歌 Map 上的 Map ID没有指定lat和long?

提问于
浏览
2

如何在没有在 Map 对象中明确设置lat和lng的情况下,基于placeID将谷歌 Map 居中?

我见过的所有例子都有一个值集,例如

var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

表单:developers.google.com

当然你可以在一个基于ID的地方获取详细信息,然后使用lat和lng将 Map 居中?

function initializeGoogleMaps() {
  jQuery('.site-content').prepend('<div id=\"map-container\"><div id=\"map-canvas\"></div></div>');

  var request = {
    placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
  };

  function callback(place, status) {
    if (status == google.maps.places.PlacesServiceStatus.OK) {
      var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
      });
    }
  }

  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    center: {
      lat: 51.509526,
      lng: -0.156314
    },
    zoom: 15
  });

  service = new google.maps.places.PlacesService(map);
  service.getDetails(request, callback);
}

1 回答

  • 5

    您可以使用places服务返回的值(或标记的位置)设置 Map 的中心:

    proof of concept fiddle

    function callback(place, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location
          });
          map.setCenter(marker.getPosition());
        }
      }
    
      var map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 15
      });
    

    code snippet:

    function initializeGoogleMaps() {
      var request = {
        placeId: 'ChIJzXBGLkQFdkgRoyT2MIxgWGw'
      };
    
      function callback(place, status) {
        if (status == google.maps.places.PlacesServiceStatus.OK) {
          var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location
          });
          map.setCenter(marker.getPosition());
        }
      }
    
      var map = new google.maps.Map(document.getElementById('map-canvas'), {
        zoom: 15
      });
    
      service = new google.maps.places.PlacesService(map);
      service.getDetails(request, callback);
    }
    google.maps.event.addDomListener(window, 'load', initializeGoogleMaps);
    
    html,
    body,
    #map-canvas {
      height: 100%;
      width: 100%;
      margin: 0px;
      padding: 0px
    }
    
    <script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
    <div id="map-canvas"></div>
    

相关问题