Przemek Wojtas
Przemek Wojtas

Reputation: 1371

google maps api get lat and lng and replace marker?

So at the moment when user enter address it adds the marker which is fine, user can also move the marker to a new location and retrieve it's lat and lng. However what it doesn't do is:

  1. Get lat and lng from the address (when pin is added to page)
  2. If address changes it adds a new marker instead of replacing existing one.

Here's the code:

var map;
function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
    zoom: 8,
    center: {lat: -34.397, lng: 150.644}
    });
    var geocoder = new google.maps.Geocoder();
    document.getElementById('postcode').addEventListener('keyup', function() {
        geocodeAddress(geocoder, map);
    });
}
function geocodeAddress(geocoder, resultsMap) {
    var address = document.getElementById('address1').value + '\xa0' + document.getElementById('address2').value +','+ document.getElementById('postcode').value;
    console.log(address);
    geocoder.geocode({'address': address}, function(results, status) {
        if (status === 'OK') {
            //if marker exist, replace it if not create it.
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location,
                title: address,
                draggable:true,
                //get lng and lat and save it to 2 seperate variables?
            });
        google.maps.event.addListener(marker, 'dragend', function(marker){
        var latLng = marker.latLng; 
        currentLatitude = latLng.lat();
        currentLongitude = latLng.lng();
        console.log(currentLatitude);
        console.log(currentLongitude);
        $("#latitude").val(currentLatitude);
        $("#longitude").val(currentLongitude);
                });
          } else {
            $('#error').append('<div class="alert alert-danger">Address not found please try again</div>');
            $(".alert-danger").fadeOut(5000);  
          }
        });
      }

Upvotes: 0

Views: 1645

Answers (3)

user7138697
user7138697

Reputation:

If you only need the one marker on the map at a time you can do the following:

  • Set the marker variable to global

    var marker;

  • The change the beginning of the function to:

    function geocodeAddress(geocoder, resultsMap) { if(marker != null){ marker.setMap(null); document.getElementById('prevlatlng').innerHTML = "LAST MARKER || lng: " + marker.getPosition().lng() +" lat: " + marker.getPosition().lat(); }

this means that if a marker is current then it will remove it.

EDIT: This will also update the div with the last successful marker added to the map

then add as usual.

JSFiddle: http://jsfiddle.net/4mtyu/2687/

Upvotes: 0

ScaisEdge
ScaisEdge

Reputation: 133380

for Get lat and lng from the address (when pin is added to page) you can

   lat = results[0].geometry.location.lat();

   lng = results[0].geometry.location.lng();

for change the marker instead of create a new one you can define a globale (window level ) var marker and assign eve to this var the result for marker creation remember tor setMap(null) for hide the old marker

var marker;
var map;

    if (marker != null) {
       marker.setMap(null);
    }

    marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location,
            title: address,
            draggable:true,
            //get lng and lat and save it to 2 seperate variables?
        });

Upvotes: 1

V&#245; Minh Phong
V&#245; Minh Phong

Reputation: 96

You can declare a global variable marker, and set marker's map is null

var map;
var marker;

function initMap() {
   map = new google.maps.Map(document.getElementById('map'), {
         zoom: 8,
         center: {lat: -34.397, lng: 150.644}
       });
   var geocoder = new google.maps.Geocoder();
   document.getElementById('postcode').addEventListener('keyup', function() 
   {
      geocodeAddress(geocoder, map);
   });
}
function geocodeAddress(geocoder, resultsMap) {
   var address = document.getElementById('address1').value + '\xa0' + 
       document.getElementById('address2').value +','+ 
       document.getElementById('postcode').value;
   console.log(address);
   geocoder.geocode({'address': address}, function(results, status) {
   if (status === 'OK') {
      //if marker exist, replace it if not create it.
      map.setCenter(results[0].geometry.location);
      if(marker && marker instanceof google.maps.Marker){
         marker.setMap(null);
         marker = null;
      }
      marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        title: address,
        draggable:true,
        //get lng and lat and save it to 2 seperate variables?
     });
       google.maps.event.addListener(marker, 'dragend', function(marker){
          var latLng = marker.latLng; 
          currentLatitude = latLng.lat();
          currentLongitude = latLng.lng();
          console.log(currentLatitude);
          console.log(currentLongitude);
          $("#latitude").val(currentLatitude);
          $("#longitude").val(currentLongitude);
      });
    } else {
      $('#error').append('<div class="alert alert-danger">Address not 
        found please try again</div>');
      $(".alert-danger").fadeOut(5000);  
    }
  });
}

Upvotes: 1

Related Questions