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

时间:2015-04-18 21:34:47

标签: javascript google-maps google-maps-api-3 google-maps-markers google-map-place

我正在尝试使用其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);

1 个答案:

答案 0 :(得分: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>