我有一个常规地图我可以放大/缩小,移动到北,南,东和西。每次我做任何动作时,我都希望获得一个新的地图矩形视图坐标,例如:lat from:x1,lat to:x2,lg from:y1,lg to:y2。
这是我在网站上初始化地图的方式:
function initMap() {
var latLng = new google.maps.LatLng(49.47805, -123.84716);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
请您指导我如何实现这一目标?
答案 0 :(得分:1)
当中心或边界发生变化时,将侦听器添加到地图中,获取地图的边界并显示四个角坐标。
google.maps.event.addListener(map,'zoom_changed', displayBounds);
google.maps.event.addListener(map,'center_changed', displayBounds);
function displayBounds() {
var bounds = map.getBounds();
var north = bounds.getNorthEast().lat();
var east = bounds.getNorthEast().lng();
var south = bounds.getSouthWest().lat();
var west = bounds.getSouthWest().lng();
var northEast = new google.maps.LatLng(north,east);
var northWest = new google.maps.LatLng(north,west);
var southEast = new google.maps.LatLng(south,east);
var southWest = new google.maps.LatLng(south,west);
// NorthEast, NorthWest, SouthEast, SouthWest
document.getElementById('coords').innerHTML = "NorthEast: "+northEast.toUrlValue(6)+"<br>NorthWest:" + northWest.toUrlValue(6) + "<br>SouthEast: "+southEast.toUrlValue(6) + "<br>SouthWest:"+southWest.toUrlValue(6)+"<br>";
}
代码段
function initMap() {
var latLng = new google.maps.LatLng(49.47805, -123.84716);
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
google.maps.event.addListener(map, 'zoom_changed', displayBounds);
google.maps.event.addListener(map, 'center_changed', displayBounds);
google.maps.event.addListenerOnce(map, 'idle', displayBounds);
}
function displayBounds() {
var bounds = map.getBounds();
var north = bounds.getNorthEast().lat();
var east = bounds.getNorthEast().lng();
var south = bounds.getSouthWest().lat();
var west = bounds.getSouthWest().lng();
var northEast = new google.maps.LatLng(north, east);
var northWest = new google.maps.LatLng(north, west);
var southEast = new google.maps.LatLng(south, east);
var southWest = new google.maps.LatLng(south, west);
// NorthEast, NorthWest, SouthEast, SouthWest
document.getElementById('coords').innerHTML = "NorthEast: " + northEast.toUrlValue(6) + "<br>NorthWest:" + northWest.toUrlValue(6) + "<br>SouthEast: " + southEast.toUrlValue(6) + "<br>SouthWest:" + southWest.toUrlValue(6) + "<br>";
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="coords"></div>
<div id="map"></div>