Код обратного геокодирования

Я работаю над составлением кода Javavscript для обратного геокодирования в картах Google. Я думал, что решил все проблемы, которые у меня были, но у меня все еще есть проблемы.

Когда я вставляю код Javascript в файл HTML, он работает без проблем. Однако, если я попытаюсь запустить javascript (с некоторыми изменениями) в виде отдельного файла, карта загружается при открытии моей формы, но когда я ввожу координаты широты и долготы и нажимаю соответствующую кнопку для обратного геокодирования, все это происходит в том, что карта обновляется.

Я прикрепил файл HTML с кодом JS, а затем отдельный файл кода JS, чтобы сделать сравнение.

HTML-файл со встроенным Javascript

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no"/>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps JavaScript API v3 Example: Reverse Geocoding</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
  var geocoder;
  var map;
  var infowindow = new google.maps.InfoWindow();
  var marker;
  function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(40.730885,-73.997383);
    var myOptions = {
      zoom: 8,
      center: latlng,
      mapTypeId: 'roadmap'
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  }

  function codeLatLng() {

    var lat = document.getElementById('Latitude').value;
    var lng = document.getElementById('Longitude').value;

    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        if (results[1]) {
          map.setZoom(11);
          marker = new google.maps.Marker({
              position: latlng, 
              map: map
          }); 
        var address= (results[1].formatted_address);
        document.getElementById('Address').value= results[1].formatted_address;
        infowindow.setContent(results[1].formatted_address);


          infowindow.open(map, marker);
        } else {
          alert("No results found");
        }
      } else {
        alert("Geocoder failed due to: " + status);
      }
    });
  }
</script>
</head>
<body onLoad="initialize()">
<div>
  <input name="Latitude" type="text" id="Latitude" size="16" maxlength="10" />
  <input name="Longitude" type="text" id="Longitude" size="16" maxlength="10" />
  <input name="Address" type="text" id="Address" size="55" />
</div>
<div>
  <input type="button" value="Reverse Geocode" onClick="codeLatLng()">
</div>
<div id="map_canvas" style="height: 90%; top:60px; border: 1px solid black;"></div>
</body>
</html>

Javascript-код

(function ReverseGeocode() {

    //This is declaring the Global variables

    var geocoder, map, marker;

    //This is declaring the 'Geocoder' variable
    geocoder = new google.maps.Geocoder();

    window.onload = function() {

    //This is creating the map with the desired options 
        var myOptions = {
            zoom: 6,
            center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                position: google.maps.ControlPosition.TOP_RIGHT
            },
            navigationControl: true,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.ZOOM_PAN,
                position: google.maps.ControlPosition.TOP_LEFT
            },
            scaleControl: true,
            scaleControlOptions: {
                position: google.maps.ControlPosition.BOTTOM_LEFT
            }
            };

        map = new google.maps.Map(document.getElementById('map'), myOptions);
        var form = document.getElementById('SearchForLocationForm');

        //This is getting the 'Latitude' and 'Longtiude' co-ordinates from the associated text boxes on the HTML form
        var lat = document.getElementById('Latitude').value;
        var lng = document.getElementById('Longitude').value;

        //This is putting the 'Latitude' and 'Longitude' variables together to make the 'latlng' variable
        var latlng = new google.maps.LatLng(lat, lng);

        // This is making the Geocode request
        geocoder.geocode({'latLng': latlng}, function(results, status) {

        // This is checking to see if the Geoeode Status is OK before proceeding    
            if (status == google.maps.GeocoderStatus.OK) {

        //This is placing the marker at the returned address    
            if (results[1]) {
          // Creating a new marker and adding it to the map
            map.setZoom(16); 
          marker = new google.maps.Marker({
            map: map, draggable:true
          });
        }

        var address= (results[1].formatted_address);

        //This is placing the returned address in the 'Address' field on the HTML form  
        document.getElementById('Address').value= results[1].formatted_address;
                }
            }
);
    };
})();

person IRHM    schedule 25.06.2011    source источник


Ответы (2)


Это короткая версия кода Хепри (спасибо!)

function getReverseGeocodingData(lat, lng) {
    var latlng = new google.maps.LatLng(lat, lng);
    // This is making the Geocode request
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status !== google.maps.GeocoderStatus.OK) {
            alert(status);
        }
        // This is checking to see if the Geoeode Status is OK before proceeding
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results);
            var address = (results[0].formatted_address);
        }
    });
}

это тоже нужно, не забывайте в голове:

<script type="text/javascript" src="https://maps.google.com/maps/api/js?sensor=false"></script>
person Sebastian Viereck    schedule 04.05.2013
comment
Большое спасибо человеку за извлечение только той части, которая нужна больше всего! работал как шарм - person Hamza Khanzada; 31.10.2019

Я взял то, что вы модифицировали, во что-то, что работает для меня...

HTML

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
    <title>Google Maps JavaScript API v3 Example: Reverse Geocoding</title>
    <link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css"
        rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    <script src="/Scripts/test.js" type="text/javascript"></script>    
</head>
<body onload="ReverseGeocode.Init()">
    <div>
        <input name="Latitude" type="text" id="Latitude" size="16" maxlength="10" />
        <input name="Longitude" type="text" id="Longitude" size="16" maxlength="10" />
        <input name="Address" type="text" id="Address" size="55" />
    </div>
    <div>
        <input type="button" value="Reverse Geocode" onclick="ReverseGeocode.ReverseCode()">
    </div>
    <div id="map_canvas" style="height: 90%; top: 60px; border: 1px solid black;">
    </div>
</body>
</html>

Это будет мой код test.js ниже

var ReverseGeocode = function () {

    //This is declaring the Global variables

    var geocoder, map, marker;

    //This is declaring the 'Geocoder' variable
    geocoder = new google.maps.Geocoder();

    function GeoCode(latlng) {

        // This is making the Geocode request
        geocoder.geocode({ 'latLng': latlng }, function (results, status) {

            if(status !== google.maps.GeocoderStatus.OK)
            {
                alert(status);
            }
            // This is checking to see if the Geoeode Status is OK before proceeding    
            if (status == google.maps.GeocoderStatus.OK) {

                //This is placing the marker at the returned address    
                if (results[0]) {
                    // Creating a new marker and adding it to the map
                    map.setZoom(16);
                    marker = new google.maps.Marker({
                        map: map, draggable: true
                    });
                    marker.setPosition(latlng);
                    map.panTo(latlng);
                }

                var address = (results[0].formatted_address);

                //This is placing the returned address in the 'Address' field on the HTML form  
                document.getElementById('Address').value = results[0].formatted_address;
            }
        });

    }

    return {

        Init: function () {

            //This is putting the 'Latitude' and 'Longitude' variables 
                            //together to make the 'latlng' variable
            //var latlng = new google.maps.LatLng(lat, lng);
            var latlng = new google.maps.LatLng(40.730885, -73.997383);

            //This is creating the map with the desired options 
            var myOptions = {
                zoom: 8,
                center: latlng,
                mapTypeId: 'roadmap'
            }

            map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

            GeoCode(latlng);
        },

        ReverseCode: function () {

            //This is getting the 'Latitude' and 'Longtiude' co-ordinates from the associated text boxes on the HTML form
            var lat = document.getElementById('Latitude').value;
            var lng = document.getElementById('Longitude').value;

            var latlng = new google.maps.LatLng(lat, lng);

            GeoCode(latlng);

        }
    };

} ();             // the parens here cause the anonymous function to execute and return

Я в основном заменил обработчик window.onload, который вы использовали, и настроил «объект» с событием инициализации, которое изначально настраивает карту. Затем я просто представил функцию, которая захватывает введенные пользователем широту/долготу и вызывает нашу оболочку геокода.

Должен работать с небольшими изменениями (за исключением большого количества обработки ошибок, которую я пропустил :-p ) для вас.

person Khepri    schedule 25.06.2011
comment
Привет, искреннее спасибо за ваш ответ и код. Я пробовал, и, к сожалению, ничего не происходит, когда я нажимаю кнопку «Обратное геокодирование». Любые идеи, пожалуйста? ОБНОВЛЕНИЕ. Мне удалось заставить это работать, это была просто отсутствующая точка с запятой. Большое спасибо за вашу помощь. С уважением - person IRHM; 25.06.2011
comment
Я загрузил пример выше для вас. guilette.net/Example.zip Просто распакуйте и запустите, и все заработает. (К вашему сведению, это мой личный домен. Если вам неудобно брать оттуда файл, дайте мне знать, и я положу файл туда, куда вы предпочитаете) РЕДАКТИРОВАТЬ: Рад, что у вас все работает! - person Khepri; 25.06.2011