Google Maps API单击带有geojson文件的信息窗口

Google maps API getting infowindow on click with geojson file

我正在使用Google Maps API,并且正在使用GeoJSON文件在地图上显示多边形。当用户在多边形内按下时,我希望显示InfoWindow并显示存储在属性中的数据。似乎很容易,但是当我单击多边形时,没有弹出任何内容。谁能解释我在做什么错?

以下是我目前正在尝试的内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
map.data.loadGeoJson('plant_bounds_2011.json');
     map.data.setStyle({
      fillColor: 'red',
      strokeWeight: 1
    });
    var infowindow = new google.maps.InfoWindow({
        content:"hello"
     });
    map.data.addListener('click', function(event) {
      let id = event.feature.getProperty('ID');
      let name = event.feature.getProperty('HORZ_ORG');
      let html = id +"" + name;
      infowindow.setContent(html); // show the html variable in the infowindow
      infowindow.setPosition(event.feature.getGeometry().get()); // anchor the infowindow at the marker
      infowindow.setOptions({pixelOffset: new google.maps.Size(0,-30)}); // move the infowindow up slightly to the top of the marker icon
      infowindow.open(map);
    });

在行上

的JavaScript代码为Uncaught TypeError: event.feature.getGeometry(...).get is not a function,这是一个JavaScript错误

1
infowindow.setPosition(event.feature.getGeometry().get()); // anchor the infowindow at the marker`

Data.Polygon几何没有.get()方法。它具有.getArray()方法(该方法返回LineStrings的数组)

要放置InfoWindow的一个位置是单击的点(在多边形中):

1
infowindow.setPosition(event.latLng);

(如果您想将信息窗口的固定点添加到GeoJson或要从多边形计算固定点,也可以执行此操作)

概念提琴证明

screenshot of resulting map

代码段:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      zoom: 4,
      center: {
        lat: -28,
        lng: 137
      },
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');
  map.data.setStyle({
    fillColor: 'red',
    strokeWeight: 1
  });
  var infowindow = new google.maps.InfoWindow({
    content:"hello"
  });
  map.data.addListener('click', function(event) {
    let id = event.feature.getProperty('ID');
    let name = event.feature.getProperty('HORZ_ORG');
    if (typeof id =="undefined") id = event.feature.getProperty('letter');
    if (typeof name =="undefined") name = event.feature.getProperty('color');
    let html = id +"" + name;
    infowindow.setContent(html); // show the html variable in the infowindow
    infowindow.setPosition(event.latLng);
    infowindow.setOptions({
      pixelOffset: new google.maps.Size(0, 0)
    }); // move the infowindow up slightly to the top of the marker icon
    infowindow.open(map);
  });
}
google.maps.event.addDomListener(window,"load", initialize);
1
2
3
4
5
6
7
8
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
1
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">