![](/img/trans.png)
[英]How can I obtain the “latitude and longitude” of the selected place with Google Maps API?
[英]How to obtain Latitude and Longitude when clicking on a rectangle in Google Maps?
我已經在Google地圖中創建了矩形,當用戶單擊矩形時,我想在代碼中獲取緯度和經度。
當我在矩形外部單擊時,將獲得緯度和經度。 但是,當我單擊矩形時,我無法獲得緯度和經度。
這是我的代碼:
var rectangle;
var map;
var infoWindow;
function initialize() {
function calcBounds(center, size) {
var n = google.maps.geometry.spherical.computeOffset(center, size.height / 2, 0).lat(),
s = google.maps.geometry.spherical.computeOffset(center, size.height / 2, 180).lat(),
e = google.maps.geometry.spherical.computeOffset(center, size.width / 2, 90).lng(),
w = google.maps.geometry.spherical.computeOffset(center, size.width / 2, 270).lng();
return new google.maps.LatLngBounds(new google.maps.LatLng(s, w),
new google.maps.LatLng(n, e));
}
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 12,
center: new google.maps.LatLng(40.689055, -89.584747),
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var rectangle = new google.maps.Rectangle({
strokeColor: '#000000',
strokeOpacity: 1,
strokeWeight: 1,
fillColor: '#008000',
fillOpacity: .2,
editable: false,
draggable: false,
map: map,
bounds: calcBounds(new google.maps.LatLngBounds(
new google.maps.LatLng(40.626805, -89.539396),
new google.maps.LatLng(40.626055, -89.538507)).getCenter(), new google.maps.Size(875, 875))
});
var rectangle = new google.maps.Rectangle({
strokeColor: '#000000',
strokeOpacity: 1,
strokeWeight: 1,
fillColor: '#008000',
fillOpacity: .2,
editable: false,
draggable: false,
map: map,
bounds: calcBounds(new google.maps.LatLngBounds(
new google.maps.LatLng(40.750555, -89.633655),
new google.maps.LatLng(40.749805, -89.632766)).getCenter(), new google.maps.Size(875, 875))
});
var rectangle = new google.maps.Rectangle({
strokeColor: '#000000',
strokeOpacity: 1,
strokeWeight: 1,
fillColor: '#008000',
fillOpacity: .2,
editable: false,
draggable: false,
map: map,
bounds: calcBounds(new google.maps.LatLngBounds(
new google.maps.LatLng(40.626805, -89.519833),
new google.maps.LatLng(40.626055, -89.518943)).getCenter(), new google.maps.Size(875, 875))
});
google.maps.event.addListener(map, 'click', function(event) {
alert("Latitude: " + event.latLng.lat() + " " + ", longitude: " + event.latLng.lng());
});
}
google.maps.event.addDomListener(window, 'load', initialize);
任何建議表示贊賞,謝謝!
您需要為每個矩形添加一個click事件。 例如:
google.maps.event.addListener(rectangle, 'click', function( event ){
alert( "Latitude: "+event.latLng.lat()+" "+", longitude: "+event.latLng.lng() );
});
您可以像在map
那樣將偵聽器附加到rectangle
map
。
google.maps.event.addListener(rectangle, 'click', function(event) {
alert('latitude: ' + event.latLng.lat() + ' , longitude: ' + event.latLng.lng());
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.