在添加多个标记并为每个标记显示信息窗口时,我遇到了新的谷歌地图 api 的问题,我的所有标记都显示了,但我的主要问题是信息窗口总是显示在一个地方,我到处都看过但似乎找不到正确的解决方案,我要显示的所有信息都来自数据库,因此我使用 xmlhttp.responseText 从另一个函数 getData 获取信息。
我的代码如下
function showMap(data){
//Changing the json respose back to the javascript array
var LongLat = eval( '(' + data + ')');
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(-26.1981, 28.0488),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var i = 0; i < LongLat.length; i++) {
latLng = new google.maps.LatLng(LongLat[i][0],LongLat[i][1]);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position:latLng,
map: map,
title: LongLat[i][0]
});
var infoWindow = new google.maps.InfoWindow();
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(point){
getData(this.position);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
infoWindow.setContent(xmlhttp.responseText);
infoWindow.open(map,marker);
}
}
});
}
}
我的getData函数如下
function getData(d){
//将对象分离为经纬度 p = (d.toString());
c = p.indexOf(',');
e = p.indexOf(')');
lat = p.substring(1,c);
lon = p.substring(c+1,e);
if(d == "results"){
var htmlCode = t;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('results').innerHTML = xmlhttp.responseText;
}
}
if(xmlhttp.readyState==4 && xmlhttp.status==200){
alert(xmlhttp.responseText);
return xmlhttp.responseText;
}
var html = xmlhttp.open("GET","mapmaker.php?lat="+lat+"&lon="+lon,true);
xmlhttp.send();
}
最佳答案
你的代码几乎是好的:)只有几个错误:
将 map 、infoWindow 设置为全局
var map = null;
var infoWindow = null;
function initialize()
{
// Fill w/ sample data
var LongLat = new Array();
LongLat[0] = new Array(-26.5, 28.5);
LongLat[1] = new Array(-26.0, 28.0);
// Creating a new map
map = new google.maps.Map(document.getElementById("map-canvas"), {
center: new google.maps.LatLng(-26.1981, 28.0488),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
infoWindow = new google.maps.InfoWindow();
for(var i = 0; i < LongLat.length; i++)
{
var latLng = new google.maps.LatLng(LongLat[i][0], LongLat[i][1]);
AddMarkerToMap(latLng, i);
} // END FOR ( LatLng)
}
将标记创建移至单独的函数。这将隐藏变量以防止更改
function AddMarkerToMap(latLng, i)
{
var marker = new google.maps.Marker({
position:latLng,
map:map
});
google.maps.event.addListener(marker, 'click', function()
{
infoWindow.setContent("Title: " + i);
infoWindow.open(map, marker);
});
}
关于javascript - 谷歌 API 信息窗口显示在谷歌地图 API 上的 1 个标记下,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9938635/