根据用户点击的位置在多边形内添加标记

时间:2015-03-30 19:41:16

标签: javascript google-maps google-maps-api-3

根据用户在polgyon中单击的位置,我显示一个infoWindow。这是通过向多边形添加单击事件侦听器来完成的:

bermudaTriangle.addListener('click', function(event) {
    var anchor = new google.maps.MVCObject();
    anchor.set("position", event.latLng);
    infowindow.open(map, anchor);
});

有没有什么办法可以在使用event.latLng检索的锚点上显示标记图标?如果我创建new google.maps.Marker而不是new google.maps.MVCObject,那么infoWindow会在多边形之外打开,然后就会离开。

示例:http://jsfiddle.net/2qyhkkok/

1 个答案:

答案 0 :(得分:1)

使用标记作为infowindow的锚点对我有用:



var map;
var marker;
var infowindow = new google.maps.InfoWindow();

function initialize() {
    var mapOptions = {
        zoom: 5,
        center: new google.maps.LatLng(24.886436490787712, -70.2685546875),
        mapTypeId: google.maps.MapTypeId.TERRAIN
    };

    var bermudaTriangle;

    var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);

    var triangleCoords = [
    new google.maps.LatLng(25.774252, -80.190262),
    new google.maps.LatLng(18.466465, -66.118292),
    new google.maps.LatLng(32.321384, -64.75737),
    new google.maps.LatLng(25.774252, -80.190262)];

    bermudaTriangle = new google.maps.Polygon({
        paths: triangleCoords,
        strokeColor: '#FF0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        fillColor: '#FF0000',
        fillOpacity: 0.35
    });

    bermudaTriangle.setMap(map);

    bermudaTriangle.addListener('click', function (event) {
        if (marker && marker.setPosition) {
          marker.setPosition(event.latLng);
          } else {
          marker = new google.maps.Marker({position: event.latLng,map:map});
            }
        infowindow.setContent("Hello, world.");
        // var anchor = new google.maps.MVCObject();
        // anchor.set("position", event.latLng);
        infowindow.open(map, marker);
    });

}

google.maps.event.addDomListener(window, 'load', initialize);

html, body, #map-canvas {
      height: 100%;
      margin: 0px;
      padding: 0px
  }

<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
&#13;
&#13;
&#13;