指定地图图标在视野范围内移动
前言:地图图标移动过程中要求可见,下面针对三种地图给出实例。
运用:GPS轨迹播放。
1、Google地图:
function calculateToView(latlng){
var bounds=map.getBounds();
//不在bounds之内则做相应的处理
if(!bounds.contains(latlng)){
var ne=bounds.getNorthEast(),sw=bounds.getSouthWest();
var northEastX=ne.x,northEastY=ne.y,southWestX=sw.x,southWestY=sw.y;
var center=map.getCenter();
var lng=center.lng(),lat=center.lat();
var px=latlng.lng(),py=latlng.lat();
if(px<=southWestX){//出左边界
var minusRt=southWestX-px;
center=new google.maps.LatLng(lat,lng-minusRt);
}else if(px>=northEastX){//出右边界
var minusRt=px-northEastX;
center=new google.maps.LatLng(lat,lng+minusRt);
}else if(py>=northEastY){//出上边界
var minusRt=py-northEastY;
center=new google.maps.LatLng(lat+minusRt,lng);
}else if(py<=southWestY){//出下边界
var minusRt=southWestY-py;
center=new google.maps.LatLng(lat-minusRt,lng);
}
map.panTo(center);
}
}
2、OpenLayers地图:
function calculateToView(lonlat){
var bounds=map.getExtent();
//不在bounds之内则做相应的处理
if(!bounds.containsLonLat(lonlat)){
var northEastX=bounds.right,northEastY=bounds.top,southWestX=bounds.left,southWestY=bounds.bottom;
var center=map.getCenter();
var lon=center.lon,lat=center.lat;
var px=latlng.lon,py=latlng.lat;
if(px<=southWestX){//出左边界
var minusRt=southWestX-px;
center=new OpenLayers.LonLat(lon-minusRt,lat);
}else if(px>=northEastX){//出右边界
var minusRt=px-northEastX;
center=new OpenLayers.LonLat(lon+minusRt,lat);
}else if(py>=northEastY){//出上边界
var minusRt=py-northEastY;
center=new OpenLayers.LonLat(lon,lat+minusRt);
}else if(py<=southWestY){//出下边界
var minusRt=southWestY-py;
center=new OpenLayers.LonLat(lon,lat-minusRt);
}
map.panTo(center);
}
}
3、ALiYun(阿里云地图):
function calculateToView(latlng){
var bounds=map.getBounds();
//不在bounds之内则做相应的处理
if(!bounds.containsLatLng(latlng)){
var ne=bounds.getNorthEast(),sw=bounds.getSouthWest();
var northEastX=ne.x,northEastY=ne.y,southWestX=sw.x,southWestY=sw.y;
var center=map.getCenter();
var lng=center.lng(),lat=center.lat();
var px=latlng.lng(),py=latlng.lat();
if(px<=southWestX){//出左边界
var minusRt=southWestX-px;
center=new AliLatLng(lat,lng-minusRt);
}else if(px>=northEastX){//出右边界
var minusRt=px-northEastX;
center=new AliLatLng(lat,lng+minusRt);
}else if(py>=northEastY){//出上边界
var minusRt=py-northEastY;
center=new AliLatLng(lat+minusRt,lng);
}else if(py<=southWestY){//出下边界
var minusRt=southWestY-py;
center=new AliLatLng(lat-minusRt,lng);
}
map.panTo(center);
}
}
注:所传参数均为经纬度坐标。