如何更改带有链接的谷歌地图中心并删除其他标记?我有这个代码
https://jsfiddle.net/m9ugbc7h/
所以,我需要创建一个链接
<a href="#" onclick="variable='latitude = 21.0241839,longitude = -86.8148164,map_zoom = 6;';return false">Ventura</a>
在这种情况下,该功能必须更改谷歌地图中心以聚焦“ventura”标记并隐藏其他标记,并且当用户单击
<a href="#" onclick="variable='latitude = 21.0241839,longitude = -86.8148164,map_zoom = 17;';return false">Dolphinaris</a>
缩放比例将发生变化,并将隐藏所有其他标记并仅显示 Dolphinaris 的标记
提前致谢
最佳答案
使map
在jQuery(document).ready
之外可见。
创建varmarkers = [];
数组。
创建标记时,向其添加自定义属性 name
,并将 marker
插入 markers
数组:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(21.0241839, -86.8148164),
map: map,
visible: true,
icon: ventura,
name: 'ventura',
});
markers.push(marker);
单击时,调用 resetMap()
函数:
<a href="#" onclick="resetMap('21.0241839', '-86.8148164', 25, 'ventura');return false;">Ventura</a>
在resetMap
函数内,将center
和zoom
设置为map
,迭代markers
,通过自定义属性 name
匹配它们 - 匹配一组可见,其他设置为不可见。
function resetMap(lat, lon, zoom, name) {
var newPos = new google.maps.LatLng(lat, lon);
map.setCenter(newPos);
map.setZoom(zoom);
markers.forEach(function(marker) {
if(marker.get('name') == name)
{
console.log('match');
marker.setVisible(true);
}
else
{
marker.setVisible(false);
}
});
工作 fiddle :https://jsfiddle.net/m9ugbc7h/1/
编辑:
问题:“有没有办法平滑地改变缩放和坐标?”
是的,使用方法:
panTo(latLng:LatLng|LatLngLiteral)
Changes the center of the map to the given LatLng. If the change is less than both the width and height of the map, the transition will be smoothly animated.
https://developers.google.com/maps/documentation/javascript/reference?csw=1
编辑2:
实现 panTo
很容易:
map.panTo(newPos);
而不是:
map.centerTo(newPos);
但是由于隐藏/显示标记在 map 上很接近,我遇到了一点“闪烁”效果,因此我在函数调用+标记显示/隐藏中添加了一些延迟:
function resetMap(lat, lon, zoom, name) {
var newPos = new google.maps.LatLng(lat, lon);
$.when( map.setZoom(zoom) ).done(function(){
$.when( map.panTo(newPos)).done(function(){
setMarkerVisibility(name);
});
});
}
显示匹配的标记现在会延迟 300 毫秒执行:
function setMarkerVisibility(name){
markers.forEach(function(marker) {
console.log(marker.get('name'));
if(marker.get('name') == name)
{
setTimeout(function(){ marker.setVisible(true); }, 300);
}
else
{
marker.setVisible(false);
}
});
}
这样看起来更流畅一点。
工作 fiddle :https://jsfiddle.net/m9ugbc7h/3/
关于javascript - 单击外部链接时隐藏谷歌地图的标记,仅显示其相应的标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31981629/