H
H
HolmesInc2016-01-28 00:06:45
JavaScript
HolmesInc, 2016-01-28 00:06:45

How to set LatLng coordinates for Google Maps?

Good afternoon. Faced such a problem. There is a code:

function load() {
          downloadUrl("getCity.php", function(data) {
          var xmlCity = data.responseXML;
          var cityMarkers = xmlCity.documentElement.getElementsByTagName("marker");
          var latCity = parseFloat(cityMarkers[0].getAttribute("lat"));
          var longCity = parseFloat(cityMarkers[0].getAttribute("lng"));
          var city = new google.maps.LatLng(latCity, longCity);
        });
          
        var map = new google.maps.Map(document.getElementById("map"), {
            center: new google.maps.LatLng(10, 10),
            zoom: 5,
            mapTypeId: 'roadmap'
          });

        var infoWindow = new google.maps.InfoWindow;
        // Change this depending on the name of your PHP file
        downloadUrl("getLocation.php", function(data) {
          var xml = data.responseXML;
          var markers = xml.documentElement.getElementsByTagName("marker");
          for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            var type = markers[i].getAttribute("type");
            var point = new google.maps.LatLng(
                parseFloat(markers[i].getAttribute("lat")),
                parseFloat(markers[i].getAttribute("lng")));
            var html = "<b>" + name + "</b> <br/>" + address;
            var icon = customIcons[type] || {};
            var marker = new google.maps.Marker({
              map: map,
              position: point,
              icon: icon.icon
            });
            bindInfoWindow(marker, map, infoWindow, html);
          }
        });
      }

      function bindInfoWindow(marker, map, infoWindow, html) {
        google.maps.event.addListener(marker, 'click', function() {
          infoWindow.setContent(html);
          infoWindow.open(map, marker);
        });
      }

      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
      }

The variable city is local and is not visible outside of the first call to the downloadUrl function. I need to insert latCity and longCity values ​​into center: new google.maps.LatLng(10, 10) instead of 10 respectively. Tried to make a global variable - value is simply not transferred. If I make global variables, in which I put the values ​​of latCity and longCity and then insert them into LatLng(), the map simply does not load. I tried a bunch of options, but it did not work out to set the starting point.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Immortal_pony, 2016-01-28
@Immortal_pony

Rewrite the downloadUrl function so that it can be synchronous. Now, at the moment when the map is being created, the script does not yet have data on latitude and longitude.
More or less like this:

var city = new google.maps.LatLng(10, 10); // Переменную все же стоит сделать глобальной. И, возможно, присвоить ей какое-то значение по умолчанию

downloadUrl("getCity.php", function(data) {
    var xmlCity = data.responseXML;
    var cityMarkers = xmlCity.documentElement.getElementsByTagName("marker");
    var latCity = parseFloat(cityMarkers[0].getAttribute("lat"));
    var longCity = parseFloat(cityMarkers[0].getAttribute("lng"));
    city = new google.maps.LatLng(latCity, longCity); // Изменяется значение, если данные от скрипта получены
}, false); // Указание, что запрос должен быть синхронным

function downloadUrl(url, callback, async) { // Дополнительная переменная для возможности указания синхронности
    async = async || true; // Задание значения по умолчанию 
    var request = window.ActiveXObject ?
        new ActiveXObject('Microsoft.XMLHTTP') :
        new XMLHttpRequest;

    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
        }
    };

    request.open('GET', url, async); // Указание синхронности запроса
    request.send(null);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question