Google地图使用地点ID添加标记

问题描述 投票:7回答:1

我正在尝试使用其PlaceID将标记放入Google地图。我有地图工作和显示,还可以添加标记(使用纬度和经度)。

下面的代码是我用来尝试使用其placeID使标记显示,但它没有显示。

function addPlaces(){
    var marker = new google.maps.Marker({
        place: new google.maps.Place('ChIJN1t_tDeuEmsRUsoyG83frY4'),
        map: map
    });
}

加载地图后调用此函数。

google.maps.event.addDomListener(window, "load", addPlaces);
javascript google-maps google-maps-api-3 google-maps-markers google-map-place
1个回答
12
投票

如果你想在地图上用place_id放置一个标记:'ChIJN1t_tDeuEmsRUsoyG83frY4',你需要向getDetails发出PlaceService请求

var service = new google.maps.places.PlacesService(map);
service.getDetails({
    placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
}, function (result, status) {
    var marker = new google.maps.Marker({
        map: map,
        place: {
            placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4',
            location: result.geometry.location
        }
    });
});

proof of concept fiddle

screenshot of resulting map

代码段:

var map;
var infoWindow;
var service;

function initialize() {
  var mapOptions = {
    zoom: 19,
    center: new google.maps.LatLng(51.257195, 3.716563)
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

  infoWindow = new google.maps.InfoWindow();
  var service = new google.maps.places.PlacesService(map);
  service.getDetails({
    placeId: 'ChIJN1t_tDeuEmsRUsoyG83frY4'
  }, function(result, status) {
    if (status != google.maps.places.PlacesServiceStatus.OK) {
      alert(status);
      return;
    }
    var marker = new google.maps.Marker({
      map: map,
      position: result.geometry.location
    });
    var address = result.adr_address;
    var newAddr = address.split("</span>,");

    infoWindow.setContent(result.name + "<br>" + newAddr[0] + "<br>" + newAddr[1] + "<br>" + newAddr[2]);
    infoWindow.open(map, marker);
  });

}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<div id="map-canvas"></div>
© www.soinside.com 2019 - 2024. All rights reserved.