在多边形mouseenter上添加InfoWindow(),每个多边形一个内容

时间:2017-07-04 08:40:37

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

我有2个(或更多)多边形,工作正常。但我想为每个多边形添加一个mouseenter事件,显示相应的信息窗口。

我在这个上下文中没有Ideia(addGeojson)怎么做

代码:

var mapOptions = {
    zoom: 4,
    scrollwheel: false,
    center: {lat: 30.162129, lng: -117.341888},          
};

geos = [{'type': 'Feature', 'geometry': {'type': 'Polygon', 'osm_type': 'relation', 'coordinates': [[[-482.2998046875,39.07890809706475],[-478.388671875,39.198205348894795],[-480.234375,36.10237644873644],[-483.72802734375,36.932330061503144],[-482.2998046875,39.07890809706475]]]}}, {'type': 'Feature', 'geometry': {'type': 'Polygon', 'osm_type': 'relation', 'coordinates': [[[-478.98193359375006,35.60371874069731],[-480.38818359375,33.687781758439364],[-477.31201171875,32.02670629333614],[-476.89453125,34.361576287484176],[-478.98193359375006,35.60371874069731]]]}}];

var map = new google.maps.Map(document.getElementById('map'), mapOptions);
for(var i = 0; i < geos.length; i++) {
	map.data.addGeoJson(geos[i]);
}

map.data.setStyle({
  	fillColor: 'orange',
  	strokeWeight: 1
});
<div id="map" style="width: 400px; height: 400px;">
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>

JSFIDDLE here

1 个答案:

答案 0 :(得分:1)

尝试这个修改过的代码,希望它有所帮助。!

    var mapOptions = {
        zoom: 4,
        scrollwheel: false,
        center: { lat: 37.140962, lng: -121.604583 },
    };

    geos = [{ 'type': 'Feature', 'geometry': { 'type': 'Polygon', 'osm_type': 'relation', 'coordinates': [[[-482.2998046875, 39.07890809706475], [-478.388671875, 39.198205348894795], [-480.234375, 36.10237644873644], [-483.72802734375, 36.932330061503144], [-482.2998046875, 39.07890809706475]]] } }, { 'type': 'Feature', 'geometry': { 'type': 'Polygon', 'osm_type': 'relation', 'coordinates': [[[-478.98193359375006, 35.60371874069731], [-480.38818359375, 33.687781758439364], [-477.31201171875, 32.02670629333614], [-476.89453125, 34.361576287484176], [-478.98193359375006, 35.60371874069731]]] } }];

    var map = new google.maps.Map(document.getElementById('map'), mapOptions);
    for (var i = 0; i < geos.length; i++) {
        var polygon = new google.maps.Data({ map: map });
        polygon.addGeoJson(geos[i]);
        //Call attachPolygonInfoWindow method here
        attachPolygonInfoWindow(polygon);
        polygon.setStyle({
            fillColor: 'orange',
            strokeWeight: 1
        });
    }

使用多边形附加信息窗口的方法。

 function attachPolygonInfoWindow(polygon) {
        var infoWindow = new google.maps.InfoWindow();
        google.maps.event.addListener(polygon, 'mouseover', function (e) {            
            infoWindow.setContent("Polygon");
            var latLng = e.latLng;
            infoWindow.setPosition(latLng);
            infoWindow.open(map);
        });
    }