javascript - 谷歌地图使用地点 ID 添加标记

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

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

The code below is what I am using to try and make the marker display using its placeID however it is not displaying.

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

此函数在 map 加载后调用。

google.maps.event.addDomListener(window, "load", addPlaces);

最佳答案

如果你想在 map 上的 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&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map-canvas"></div>

关于javascript - 谷歌地图使用地点 ID 添加标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29723134/

相关文章:

javascript - JSF:Javascript google map API - 标记获得相同的标题

javascript - 来自数据库的预填充模式(非 Bootstrap )

javascript - 谷歌应用程序脚本 : How to change text color of label on hover?

google-maps - 单击时将标记添加到 Google map

java - GoogleMap 在 Android 中同时返回 null 和非 null

javascript - Google map 关闭街景 (JQuery)

javascript - 如何预加载谷歌地图的某些部分?

javascript - Angularjs 和 ui-router,在浏览器刷新时刷新所有父状态

javascript - 使用 html css 和 javascript 的日历

google-maps-api-3 - 设置 KML 图层透明度