我最终得到了这个代码来显示谷歌地图:
<script>
function init_map() {
// Create an array of styles.
var styles = [
{
"featureType": "water",
"elementType": "geometry",
"stylers": [
{
"color": "red"
},
{
"lightness": 25
}
]
}
];
var myOptions = {
mapTypeControlOptions: {
mapTypeIds: ['Map']
},
center: new google.maps.LatLng(40.514459, 0.13461),
zoom:3,
disableDefaultUI: false,
mapTypeId: 'Map',
scrollwheel: false,
navigationControl: true,
scaleControl: true,
};
var div = document.getElementById('gmap_canvas');
var map = new google.maps.Map(div, myOptions);
var styledMapType = new google.maps.StyledMapType(styles, { name: 'Map' });
map.mapTypes.set('Map', styledMapType);
var bounds = new google.maps.LatLngBounds();
marker = new google.maps.Marker({
map: map,
//position: new google.maps.LatLng(56.6789471,-0.34535),
icon: "images/marker.png"
});
var markers = [
['One', 11.232214,122.155547],
['Two', 39.555535,-87.5462367],
['Three', 48.3563671,-1.34554825],
];
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
icon: "images/ico.png",
title: markers[i][0]
});
}
}
if (document.getElementById("gmap_canvas")) {
google.maps.event.addDomListener(window, 'load', init_map);
}
上面的代码创建了具有多个点(一、二、三)的谷歌地图。
我想做的是列出这些联系点,例如:
<div class="point">Contact ONE</div>
<div class="point">Contact TWO</div>
<div class="point">Contact THREE</div>
当我点击此联系 map 时,应该缩放到这一点。 我发现了这一点,但示例仅显示一个点,并且事件是在标记单击时触发的,而不是自定义 Html 元素。
https://developers.google.com/maps/documentation/javascript/examples/event-simple
最佳答案
您应该将 map
变量设置为全局变量,并将全局变量定义为标记数组(在示例中:markerArr
)。(在 init_map( )
函数):
<script>
var map;
var markerArr = [];
function init_map() {...
...
然后在 for 循环中将每个标记添加到该数组中:
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
icon: "images/ico.png",
title: markers[i][0]
});
markerArr.push(marker); // Add the marker to the array
}
然后创建一个带有整数参数的简单函数,我们将其称为jumpToMarker
,我们可以在其中缩放并跳转到所选标记。:
function jumpToMarker(cnt){
map.panTo(markerArr[cnt].getPosition());
map.setZoom(4);
}
最后在 DOM 中设置 div 及其 onclick 事件,位于 map 的 div 之后:
<div class="point"><a href="javascript:void(0);" onclick="jumpToMarker(0)">Contact ONE</a></div>
<div class="point"><a href="javascript:void(0);" onclick="jumpToMarker(1)">Contact TWO</a></div>
<div class="point"><a href="javascript:void(0);" onclick="jumpToMarker(2)">Contact THREE</a></div>
希望这有帮助!
关于javascript - 单击元素后如何显示和缩放 Google map v3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37436285/