javascript - 如何在 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');
}
解决方案
打开InfoWindow
鼠标悬停:
- 创建一个
InfoWindow
:
var infowindow = new google.maps.InfoWindow({
pixelOffset: new google.maps.Size(0, -40) // offset for icon
});
- 将 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>
推荐阅读
- c# - 如何路由 401 和 403 错误?
- c++ - 您将如何嵌套结构?
- xml - XSLT - 未设置根元素
- rest - 为什么使用 Google Cloud Drive Rest API file.list 无法获取所有文件?
- python - 如何在 py 编辑器中添加多个 @app.route?
- python-3.x - Python3:在空的熊猫数据框中添加多列行
- php - 有时 ftp_connect() 不能在 php 中工作,其余时间它工作得很好
- javascript - 如何在另一个页面中使用表单选择值
- dvd - 如何将 DVD 复制到本地系统?
- solid-principles - 关于 SOLID 编程实践的实用问题