我有这个功能,在点击一个标记后,在与项目相关的点之间画一条线。
function showDetails(itemId)
{
var newlatlng = itemId.position;
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "index.php?r=items/ajaxdetails&id="+itemId.indice,
false);
xmlhttp.send();
var checkins = JSON.parse(xmlhttp.responseText);
var numeroCheckins = checkins.length;
var polylineCheckins = [];
var bounds = new google.maps.LatLngBounds();
for (counter = 0; counter< numeroCheckins; counter++)
{
var posizione = new google.maps.LatLng(checkins[counter].lat,
checkins[counter].long);
polylineCheckins[counter] = posizione;
bounds.extend(posizione);
}
var polyline = new google.maps.Polyline({
path: polylineCheckins,
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 5
});
polyline.setMap(map);
map.fitBounds(bounds);
}一切都正常,但如果多次调用此函数,则总是显示前一行。我尝试使用方法setMap(null),但没有成功,试图重置多段线。
我希望在绘制新的多段线之前删除前一条多段线的结果。
多谢你们的支持
发布于 2012-06-01 22:11:42
在地图上仅为showDetails保留一条多段线的最简单方法是创建一个全局多段线变量。这样,每次调用showDetails时,全局变量都会被修改。
现在,每次showDetails运行时都会创建一条新的折线,并且不会返回对它的引用,因此我看不到将前一条线的映射设置为null的方法。
// GLOBAL
var detailsPolyline = new google.maps.Polyline({
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 5
});showDetails内幕
detailsPolyline.setPath(polylineCheckins);
detailsPolyline.setMap(map);
map.fitBounds(bounds);下面是我使用的全部测试用例,因为我没有创建自己的对象的php文件
var map;
var mapOptions = { center: new google.maps.LatLng(0.0, 0.0), zoom: 2,
mapTypeId: google.maps.MapTypeId.ROADMAP };
function initialize() {
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
showDetails([ {lat: 20, long: 0},
{lat: 20, long: 10},
{lat: 30, long: 20}]);
showDetails([ {lat: 10, long: 0},
{lat: 10, long: 10},
{lat: 20, long: 20}]);
}
var detailsPolyline = new google.maps.Polyline({
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 5
});
function showDetails(checkins)
{
var numeroCheckins = checkins.length;
var polylineCheckins = [];
var bounds = new google.maps.LatLngBounds();
for (counter = 0; counter< numeroCheckins; counter++)
{
var posizione = new google.maps.LatLng(checkins[counter].lat, checkins[counter].long);
polylineCheckins[counter] = posizione;
bounds.extend(posizione);
}
detailsPolyline.setPath(polylineCheckins);
detailsPolyline.setMap(map);
map.fitBounds(bounds);
}发布于 2012-06-01 22:10:36
您将在函数本身中定义polyline变量,因此一旦函数完成,该变量就会超出任何其他方法(如setMap(null))的作用域。
有几种方法可以做到这一点。最简单的方法是将函数外部的多段线定义为全局变量:
var polyline = null;
function showDetails(itemId)
{
if (polyline != null)
{
polyline.setMap(null);
polyline = null;
}
/* more code */
polyline = new google.maps.Polyline({
path: polylineCheckins,
strokeColor: "#FF0000",
strokeOpacity: 0.5,
strokeWeight: 5
});
polyline.setMap(map);
map.fitBounds(bounds);
}https://stackoverflow.com/questions/10851421
复制相似问题