加载loadGeoJson调用后如何点击标记?

时间:2014-12-28 05:23:44

标签: google-maps

我在GeoJson文件中有一长串的点,我正在加载它:

map.data.loadGeoJson()调用。

每个点在谷歌地图上都有一个图标。

当用户单击其中一个点时,我有一个点击侦听器,然后显示一个信息窗口。我不确定如何获取已经在监听器内点击的标记,以告诉infoWindow在哪里发布,你们知道吗?

1 个答案:

答案 0 :(得分:0)

您可以使用(事件为DataMouseEvent object)获取点击标记的位置:

event.feature.getGeometry().get()

工作代码段:



// global variables
var infowindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();

function initialize() {
  // Create a simple map.
  features = [];
  map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 4,
    center: {
      lat: -28,
      lng: 137.883
    }
  });
  google.maps.event.addListener(map, 'click', function() {
    infowidow.close();
  });
  // process the loaded GeoJSON data.
  google.maps.event.addListener(map.data, 'addfeature', function(e) {
    if (e.feature.getGeometry().getType() === 'Point') {
      bounds.extend(e.feature.getGeometry().get());
      map.fitBounds(bounds);
    }
  });
  map.data.addGeoJson(data);
  // Set click event for each feature.
  map.data.addListener('click', function(event) {
    infowindow.setContent('<div style="width:50px;">' + event.feature.getProperty('htmlContent') + '</div>');
    infowindow.setOptions({
      pixelOffset: new google.maps.Size(0, -36)
    });
    infowindow.setPosition(event.feature.getGeometry().get());
    infowindow.open(map);
    google.maps.event.addListenerOnce(infowindow, 'domready', function() {
      infowindow.close();
      infowindow.open(map);
    });
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
var data = {
  "type": "FeatureCollection",
  "features":

    [

    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [-73.563032, 45.495403]
      },
      "properties": {
        "htmlContent": "point 0"
      }
    },

    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [-73.549762, 45.559673]
      },
      "properties": {
        "htmlContent": "point 1"
      }
    }
  ]

};
&#13;
html,
body,
#map-canvas {
  height: 100%;
  margin: 0px;
  padding: 0px;
  width: 100%;
}
&#13;
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map-canvas"></div>
&#13;
&#13;
&#13;