简短版
在Google Maps API中,如何正确使用唯一多边形ID,以便我不会在彼此之上呈现重复的多边形?
长版
我想在Google地图上叠加地理热图数据。热图由方形瓷砖组成。我从JSON格式的API服务器获取了瓷砖坐标以及它们的ID和分数。当页面加载时,我将热图贴图渲染为多边形对象并且它们显示正确,但是如果我将地图拖动一半以使某些贴图仍然可见,则会重新获取相同的贴图(以及新贴图)从服务器并在现有切片的顶部呈现。这会导致颜色变化并破坏热图。 我将来自API服务器的唯一整数ID添加为Polygon对象中的ID,但它不能解决问题,我不明白为什么。
以下是代码(为简洁起见,仅显示相关部分):
function initMap() {
var center = new google.maps.LatLng(37.461021, -122.163314);
map = new google.maps.Map(document.getElementById('map'), {center: center, zoom: 11});
/* 'bounds_changed' event happens too frequently
better to use 'idle' event that fires when map changed and now is idle.
*/
google.maps.event.addListener(map, 'idle', redrawMap);
}
function redrawMap() {
/* redraw map's heatmap tiles and pollution sources */
var mapBounds = map.getBounds();
var ne = mapBounds.getNorthEast();
var sw = mapBounds.getSouthWest();
var url = 'https://<my_api_server/dev/map_data' +
'?ne_lat=' + ne.lat() + '&ne_lng=' + ne.lng() + '&sw_lat=' + sw.lat() + '&sw_lng=' + sw.lng();
/* get data from API server */
$.getJSON({
url: url,
success: function(result, status, xhr){
mapData = result;
// fetched JSON contains 'tiles' key with all the data in the value
var tileData = mapData['tiles'];
addHeatmapTiles(tileData);
}
});
}
function addHeatmapTiles(tileData) {
/* show heatmap tiles for sources on the map */
var num_tiles = tileData.length;
for(var c = 0; c < num_tiles; c++){
var tile = tileData[c];
var polygon = new google.maps.Polygon({
id: tile['id'],
fillColor: colors[tile['score']], // colors is a hash with score->color values
fillOpacity: 0.6,
map: map,
strokeWeight: 0,
paths: tile['tile_coords']
});
}
}
来自服务器的示例JSON数据:
{
"tiles":[
{
"id":63125,
"tile_coords":[
{"lat":37.446584, "lng":-122.129749},
{"lat":37.439548, "lng":-122.127375},
{"lat":37.437663, "lng":-122.136237},
{"lat":37.444699, "lng":-122.138612}
],
"score":8
},
{
"id":60830,
"tile_coords":[
{"lat":37.447649, "lng":-122.158945},
{"lat":37.440613, "lng":-122.156571},
{"lat":37.438728, "lng":-122.165433},
{"lat":37.445764, "lng":-122.167808}
],
"score":8
},
],
"other_data": "..."
}
P.S。我承认我是一个后端人,只是为这项任务学习了JavaScript,但我花了好几天尝试不同的方法,但它仍然无效。我变得绝望,并会感激任何帮助。
我还要感谢有关优化此代码的任何其他建议。例如,放弃这个并使用google.maps.Data.loadGeoJson()
会更快吗?我尝试了它,但它既没有渲染任何瓷砖也没有返回任何错误。如果这应该是单独的帖子,请建议我将使用提供的代码段创建一个。