我有HTML页面,其中包含Google地图。我有计时器,它调用函数,它移动地图。地图被移动但每次都闪烁。那么如何修复这个错误?
function Replace(lt,ln)
{
var location = new google.maps.LatLng(lt, ln);
var myOptions = {
zoom: 15,
center: location,
mapTypeControl: true,
mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
navigationControl: true,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var companyPos = new google.maps.LatLng(lt, ln);
var companyMarker = new google.maps.Marker({
position: companyPos,
map: map,
title: "Test"
});
}
答案 0 :(得分:0)
这不是一个错误,每次运行此函数时都会创建一个新的map-instance(导致闪烁的原因)。
分开代码,在第一次运行时创建地图/标记实例,稍后只更新地图中心和标记位置:
function Replace(lt,ln){
var location = new google.maps.LatLng(lt, ln);
var companyPos = new google.maps.LatLng(lt, ln);
//map not created yet
if(!window.map){
var myOptions = {
zoom: 3,
center: location
};
//Note: map and companyMarker must be global
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
companyMarker = new google.maps.Marker({
position: companyPos,
map: map,
title: "Test"
});
}
//map already initialized, update center and position
else{
map.setCenter(location);
companyMarker.setPosition(companyPos);
}
}