JS:
var map;
function pageLoad() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(34.454543, 35.812997),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
}
function getRandomArbitary(min, max) {
return Math.random() * (max - min) + min;
}
function SetLocation() {
var latitude = getRandomArbitary(1, 30);
var longitude = getRandomArbitary(1, 30);
var locationlatLng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
'position': locationlatLng,
'map': map
});
map.panTo(locationlatLng);
}
HTML:
<div id="map" style="width: 900px; height: 600px">
<a href="javascript:void(0)" onclick="SetLocation();">Set Custom Location</a>
当用户点击设置自定义位置时,会创建一个新标记,并且地图会对其进行处理,但是如何在创建新标记时动态显示信息窗口?
答案 0 :(得分:0)
创建后点击标记(使用google.maps.event.trigger)(当然,您需要一个点击监听器来打开infowindow,以及一些内容用于infowindow):
var map;
var infowindow;
function pageLoad() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: new google.maps.LatLng(34.454543, 35.812997),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infowindow = new google.maps.InfoWindow();
}
function getRandomArbitary(min, max) {
return Math.random() * (max - min) + min;
}
function SetLocation() {
var latitude = getRandomArbitary(1, 30);
var longitude = getRandomArbitary(1, 30);
var locationlatLng = new google.maps.LatLng(latitude, longitude);
var marker = new google.maps.Marker({
'position': locationlatLng,
'map': map
});
google.maps.event.addListener(marker,'click',function(e){
if (e && e.latLng) {
infowindow.setContent("location:" +e.latLng);
} else {
infowindow.setContent("location:" +marker.getPosition());
}
infowindow.open(map,marker);
});
google.maps.event.trigger(marker,'click');
map.panTo(locationlatLng);
}
google.maps.event.addDomListener(window, 'load', pageLoad);