2015-04-17 88 views
0

IM製作解決方案,它的地理編碼,我可以從住址得到COORDS,並把標記在這個住址,即時試圖使這個標誌draggabele,每次我改變標記位置與鼠標,我必須得到新的cooords,有人可以幫助我嗎?如何獲取拖動的標記經緯度信息

編輯:用event.addlistner

解決方案,這是我的代碼(JS + HTML)

<!DOCTYPE html> 
<html> 
<head> 
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"> 
<meta charset="utf-8"> 
<title>Geocoding service</title> 
<style> 
    html, body, #map-canvas { 
    height: 100%; 
    margin: 0px; 
    padding: 0px 
    } 
    #panel { 
    position: absolute; 
    top: 5px; 
    left: 50%; 
    margin-left: -180px; 
    z-index: 5; 
    background-color: #fff; 
    padding: 5px; 
    border: 1px solid #999; 
    } 
</style> 
<script src="https://maps.googleapis.com/maps/api/js? v=3.exp&signed_in=true"></script> 
<script> 
var geocoder; 
var map; 
function initialize() { 
    geocoder = new google.maps.Geocoder(); 
    var latlng = new google.maps.LatLng(34.042145, -4.997128); 
    var mapOptions = { 
    zoom: 5, 
    center: latlng 
} 
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
} 

    function codeAddress() { 
    var address = document.getElementById('address').value; 
var lg; 
var lat; 
geocoder.geocode({ 'address': address}, function(results, status) { 
    if (status == google.maps.GeocoderStatus.OK) { 
    map.setCenter(results[0].geometry.location); 

    map.setZoom(16); 

    var lat = results[0].geometry.location.lat(); 
    document.getElementById('latitude').value = lat; 

    var lg = results[0].geometry.location.lng(); 
    document.getElementById('longitude').value = lg; 


    var marker = new google.maps.Marker({ 
     map: map, 
     position: results[0].geometry.location, 
     draggable : true 
    }); 
} 

    else { 
    alert('Geocode was not successful for the following reason: ' + status); 
} 
}); 
} 

google.maps.event.addDomListener(window, 'load', initialize); 

</script> 
</head> 
<body> 
    <div id="panel"> 
    <input id="address" type="textbox"> 
    <input id="latitude" type="textbox" > 
    <input id="longitude" type="textbox" > 
    <input type="button" value="Geocode" onclick="codeAddress()"> 
</div> 
<div id="map-canvas"></div> 
</body> 
</html> 
+1

HTTP的可能重複:/ /stackoverflow.com/questions/11030730/getting-coordinates-of-marker-in-google-maps-api請看看那裏 – AlexG

回答

1

使用谷歌地圖getPosition功能:

google.maps.event.addListener(marker,"dragend",function(){ 
    document.getElementById("latitude").value=marker.getPosition().lat(); 
    document.getElementById("longitude").value=marker.getPosition().lng(); 
}); 
+0

我應該把它放在初始化()還是在那裏,我真的很困惑 –

+0

由於'marker'只在您的'codeAddress()'函數中聲明,所以您還需要將上面的代碼放在同一個函數中。 – Shaggy

+0

感謝毛茸茸的它是有幫助的:) –