google maps api get lat and lng and replace marker?

戏子无情 提交于 2019-12-25 09:28:42

问题


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);  
          }
        });
      }

回答1:


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);  
    }
  });
}



回答2:


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?
        });



回答3:


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/



来源:https://stackoverflow.com/questions/44701450/google-maps-api-get-lat-and-lng-and-replace-marker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!