Ismaili Alaoui smail
Ismaili Alaoui smail

Reputation: 136

how to fetch draggable marker latlng information

im making a solution that does the geocoding , i can get coords from adresse , and put a marker over this adresse , im trying to make this marker draggabele and everytime i change the marker position with the mouse , i must get the new cooords , can someone help me ?

edit : Solution with event.addlistner

this is my code (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>

Upvotes: 0

Views: 128

Answers (1)

Shaggy
Shaggy

Reputation: 6796

Use Google Maps' getPosition function:

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

Upvotes: 1

Related Questions