首页 > 解决方案 > 如何在 Google 地图中的标记上添加显示 .geojson 属性的悬停框?

问题描述

我正在做一个项目,我正在使用 .geojson 文件在 Google Maps API 中绘制数百个房屋,该文件包含所有这些房屋作为具有众多属性的功能。我已经让我的 .js 文件加载 .geojson 文件并将每个家显示为地图上的标记,但是我无法弄清楚如何与这些点进行交互。当悬停在该点上时,我试图让这些点显示一个带有其地址(列为属性之一)的文本框。

到目前为止,这就是我为我的 .js 文件编写的所有内容 -

function initMap() {
  var map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: 41.8963964, lng: -87.6864236},
          zoom: 13
  });

  map.data.loadGeoJson('data_table.json', 'Full Address');
}

https://i.stack.imgur.com/oBsJf.png

信息窗口的图像 这是我在将鼠标悬停在某个点上时尝试创建的文本框类型的图像。

标签: javascriptgoogle-mapsgeojson

解决方案


打开InfoWindow鼠标悬停:

  1. 创建一个InfoWindow
var infowindow = new google.maps.InfoWindow({
  pixelOffset: new google.maps.Size(0, -40) // offset for icon
});
  1. 将 mouseover 事件侦听器添加到Data Layer打开InfoWindow,并在其中显示适当的属性(在“prop0”下方):
map.data.addListener('mouseover', function(evt) {
  infowindow.setContent(evt.feature.getProperty('prop0'));
  infowindow.setPosition(evt.feature.getGeometry().get());
  infowindow.open(map);
});

概念证明小提琴

信息窗口打开时生成的地图的屏幕截图

代码片段:

var map;

function initMap() {
  map = new google.maps.Map(document.getElementById('map'), {
    zoom: 4,
    center: {
      lat: -28,
      lng: 137
    }
  });
  var infowindow = new google.maps.InfoWindow({
    pixelOffset: new google.maps.Size(0, -40)
  });
  var bounds = new google.maps.LatLngBounds();
  map.data.addListener('addfeature', function(evt) {
    if (evt.feature.getGeometry().getType() == 'Point') {
      bounds.extend(evt.feature.getGeometry().get());
      map.fitBounds(bounds);
    }
  })
  map.data.addGeoJson(geoJson);
  map.data.addListener('mouseover', function(evt) {
    console.log(evt.feature.getProperty('prop0'));
    infowindow.setContent(evt.feature.getProperty('prop0'));
    infowindow.setPosition(evt.feature.getGeometry().get());
    infowindow.open(map);
  })
}
var geoJson = {
  "type": "FeatureCollection",
  "features": [{
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [-73.563032, 45.495403]
      },
      "properties": {
        "prop0": "value0"
      }
    },
    {
      "type": "Feature",
      "geometry": {
        "type": "Point",
        "coordinates": [-73.549762, 45.559673]
      },
      "properties": {
        "prop0": "value1"
      }
    }
  ]
}
html,
body,
#map {
  height: 100%;
  margin: 0;
  padding: 0;
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>


推荐阅读