Google maps v3 перетаскиваемый маркер - PullRequest
56 голосов
/ 16 апреля 2011

Я новичок в Google Maps, и я пытаюсь узнать это.

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

Это моя позиция маркера, когда я инициализирую позицию маркера, чем знаю название места (например: улица XY, Нью-Йорк,), но из-за перетаскиваемой опции она меняется, и мой вопрос заключается в том, как могу ли я получить новое название места, какой обработчик событий мне нужен.

Ответы [ 3 ]

118 голосов
/ 17 апреля 2011

Наконец я нашел ответ:

marker = new google.maps.Marker(
{
    map:map,
    draggable:true,
    animation: google.maps.Animation.DROP,
    position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'dragend', function() 
{
    geocodePosition(marker.getPosition());
});

function geocodePosition(pos) 
{
   geocoder = new google.maps.Geocoder();
   geocoder.geocode
    ({
        latLng: pos
    }, 
        function(results, status) 
        {
            if (status == google.maps.GeocoderStatus.OK) 
            {
                $("#mapSearchInput").val(results[0].formatted_address);
                $("#mapErrorMsg").hide(100);
            } 
            else 
            {
                $("#mapErrorMsg").html('Cannot determine address at this location.'+status).show(100);
            }
        }
    );
}
22 голосов
/ 12 сентября 2016

Установить позицию на карте с помощью широты и длины и сделать маркер перетаскиваемым

Переменная адреса используется для заголовка.Его можно игнорировать.

перетаскиваемый: true делает маркер перетаскиваемым.

Используйте прослушиватель событий google.maps.event.addListener (маркер, 'dragend', функция (маркер) Чтобы прослушать изменения положения маркера

function showMap(lat,lang,address) {
var myLatLng = {lat: lat, lng: lang};

    var map = new google.maps.Map(document.getElementById('map_canvas'), {
      zoom: 17,
      center: myLatLng
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: address,
      draggable:true,
    });

    google.maps.event.addListener(marker, 'dragend', function(marker){
        var latLng = marker.latLng; 
        currentLatitude = latLng.lat();
        currentLongitude = latLng.lng();
        jQ("#latitude").val(currentLatitude);
        jQ("#longitude").val(currentLongitude);
     }); 
}
0 голосов
/ 10 января 2019

Вот код, который получает перетаскиваемый маркер с положением в текстовом поле:

/**
 *Receiving the value of text box and type done conversion by Number() 
 */
var latitude = Number(document.getElementById("la").value);
var longitude = Number(document.getElementById("lo").value);

function initMap() {
  /**
   *Passing the value of variable received from text box
   **/
  var uluru = {
    lat: latitude,
    lng: longitude
  };
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 7,
    center: uluru
  });
  marker = new google.maps.Marker({
    map: map,
    draggable: true,
    animation: google.maps.Animation.DROP,
    position: uluru
  });
  google.maps.event.addListener(marker, 'dragend',
    function(marker) {
      var latLng = marker.latLng;
      currentLatitude = latLng.lat();
      currentLongitude = latLng.lng();
      $("#la").val(currentLatitude);
      $("#lo").val(currentLongitude);
    }
  );
}
#map {
  height: 400px;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="map"></div>
Latitude <input type="text" id="la" name="latitude" value="28.39"> Longitude<input type="text" id="lo" name="longitude" value="84.12">

<!--Google Map API Link-->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=YOURAPIKEYHERE&callback=initMap">

Пожалуйста, используйте jQuery во главе

...