Можно ли получить широту и долготу перетаскиваемого маркера на карте (используя javascript) в форму в HTML?

Я пытаюсь получить широту и долготу перетаскиваемого маркера на картах Google. Мне нужно, чтобы эти значения попадали непосредственно в атрибут value в файле <input type="text">. Мне удалось это сделать, единственная проблема в том, что я не знаю, как добавить геокодер, чтобы пользователь мог ввести свой собственный адрес и получить широту и долготу, но они также должны быть альбе, чтобы перетащить маркер в случай, когда карты Google не точны. Я оставлю свой код здесь. Цените, если кто-нибудь может помочь.

HTML

<!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> </head> <body> <input type="text" id="latitude" placeholder="latitude"> <input type="text" id="longitude" placeholder="longitude"> <div id="map" style="width:500px; height:500px"></div> <p><input class="postcode" id="Postcode" name="Postcode" type="text"> <input type="submit" id="findbutton" value="Find" /></p> </body> </html>

JavaScript

        function initialize() {
        var $latitude = document.getElementById('latitude');
        var $longitude = document.getElementById('longitude');
        var latitude = 50.715591133433854
        var longitude = -3.53485107421875;
        var zoom = 16;
        var geocoder;

        var LatLng = new google.maps.LatLng(latitude, longitude);

        var mapOptions = {
            zoom: zoom,
            center: LatLng,
            panControl: false,
            zoomControl: false,
            scaleControl: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }   

        var map = new google.maps.Map(document.getElementById('map'),mapOptions);

        geocoder = new google.maps.Geocoder();  

        var marker = new google.maps.Marker({
            position: LatLng,
            map: map,
            title: 'Drag Me!',
            draggable: true
        });

        google.maps.event.addListener(marker, 'dragend', function(marker){
            var latLng = marker.latLng;
            $latitude.value = latLng.lat();
            $longitude.value = latLng.lng();
        });


    }
    $(document).ready(function () {

        initialize();

        $('#findbutton').click(function (e) {
            var address = $(PostCodeid).val();
            geocoder.geocode({ 'address': address }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    map.setCenter(results[0].geometry.location);
                    marker.setPosition(results[0].geometry.location);
                    $(latitude).val(marker.getPosition().lat());
                    $(longitude).val(marker.getPosition().lng());
                } else {
                    alert("Geocode was not successful for the following reason: " + status);
                }
            });
            e.preventDefault();
        });
    });

person DavidCamhi    schedule 26.11.2014    source источник
comment
В вашем вопросе нет кода, использующего геокодер. Что вы пробовали, что не сработало?   -  person geocodezip    schedule 26.11.2014
comment
Я не знаю, как реализовать геокодер, не нарушая этот код. У меня есть другая страница, на которой я ставлю маркер по данному адресу, но не могу получить широту и долготу.   -  person DavidCamhi    schedule 26.11.2014
comment
Вы можете опубликовать свою лучшую попытку добавления геокодера. Ответ на ваш вопрос на данный момент: (1.) добавить google.maps.Geocoder. (2.) вызвать его с предоставленным адресом, используя возвращенные координаты, чтобы разместить маркер на карте.   -  person geocodezip    schedule 26.11.2014
comment
В вашем HTML нет текстового поля для ввода адреса...   -  person geocodezip    schedule 26.11.2014
comment
Я обновил вопрос своей попыткой добавить геокодер.   -  person DavidCamhi    schedule 26.11.2014


Ответы (1)


  1. добавьте google.maps.Geocoder.
  2. вызовите его с предоставленным адресом, используя возвращенные координаты, чтобы разместить маркер на карте.
  3. получить координаты этого маркера

рабочий фрагмент:

var geocoder = new google.maps.Geocoder();
var marker = null;
var map = null;
function initialize() {
      var $latitude = document.getElementById('latitude');
      var $longitude = document.getElementById('longitude');
      var latitude = 50.715591133433854
      var longitude = -3.53485107421875;
      var zoom = 16;

      var LatLng = new google.maps.LatLng(latitude, longitude);

      var mapOptions = {
        zoom: zoom,
        center: LatLng,
        panControl: false,
        zoomControl: false,
        scaleControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      }

      map = new google.maps.Map(document.getElementById('map'), mapOptions);
      if (marker && marker.getMap) marker.setMap(map);
      marker = new google.maps.Marker({
        position: LatLng,
        map: map,
        title: 'Drag Me!',
        draggable: true
      });

      google.maps.event.addListener(marker, 'dragend', function(marker) {
        var latLng = marker.latLng;
        $latitude.value = latLng.lat();
        $longitude.value = latLng.lng();
      });


    }
    initialize();
    $('#findbutton').click(function (e) {
        var address = $("#Postcode").val();
        geocoder.geocode({ 'address': address }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                marker.setPosition(results[0].geometry.location);
                $(latitude).val(marker.getPosition().lat());
                $(longitude).val(marker.getPosition().lng());
            } else {
                alert("Geocode was not successful for the following reason: " + status);
            }
        });
        e.preventDefault();
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
    <input type="text" id="latitude" placeholder="latitude">
    <input type="text" id="longitude" placeholder="longitude">
    <div id="map" style="width:500px; height:500px"></div>
    <p><input class="postcode" id="Postcode" name="Postcode" type="text" value="New York, NY">
    <input type="submit" id="findbutton" value="Find" /></p>

person geocodezip    schedule 26.11.2014
comment
Это был бы другой вопрос. Вы включаете библиотеку мест? - person geocodezip; 26.11.2014