google maps api get lat和lng并替换marker?

时间:2017-06-22 13:53:37

标签: javascript jquery google-maps google-maps-api-3

因此,当用户输入地址时,它会添加好的标记,用户也可以将标记移动到新位置并检索它的lat和lng。然而,它没有做的是:

  1. 从地址获取lat和lng(当引脚添加到页面时)
  2. 如果地址更改,则会添加新标记,而不是替换现有标记。
  3. 以下是代码:

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

3 个答案:

答案 0 :(得分:1)

您可以声明全局变量marker,并设置标记的地图为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);  
    }
  });
}

答案 1 :(得分:1)

从地址获取lat和lng(当引脚添加到页面时),您可以

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

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

更改标记而不是创建新标记,您可以定义一个globale(窗口级别)var标记,并为此var指定eve标记创建的结果记住tor setMap(null)隐藏旧标记

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

答案 2 :(得分:0)

如果您一次只需要地图上的一个标记,则可以执行以下操作:

  • 将标记变量设置为全局

    var marker;

  • 将函数的开头更改为:

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

这意味着如果标记是当前的,那么它将删除它。

编辑:这也将更新div,并将最后成功标记添加到地图

然后像往常一样添加。

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