-1

I'm trying to get my google maps app to wait for an answer from an ajax call from a db call using php. I know I need to use callbacks but I'm unsure how to implement them in this case since geocoder api is also async.

I tried answer from How to pass variables and data from PHP to JavaScript? and Using gettext with Javascript from PHP via XMLHttpRequest but I'm unsure how to edit it to work with my case.

db.php

$mysqli = new mysqli("host", "user", "pass", "db");
(perform query)...
echo json_encode($result_assoc_array);

location.php

<html>
(html boilerplate)...
<body>
<div id="map"></div>
<script>
var map;
var homeAddress;

var oReq = new XMLHttpRequest();
oReq.onload = function() {
    homeAddress = JSON.parse(this.responseText).address; //main field I want is address
};
oReq.open("get", "db.php", true);

oReq.send();

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 15,
    });

    var bounds = new google.maps.LatLngBounds();
    var geocoder = new google.maps.Geocoder();
    var markers = [];

    geocoder.geocode({
        'address': JSON.stringify(homeAddress)
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            console.log(results);
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            bounds.extend(marker.position);
            markers.push(marker);
        } else {
            alert("Geocode was not successful for the following reason: " + status);
        }
    });
 (more logic)
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=myKey&callback=initMap&libraries=geometry" async defer></script>
</body>
</html>

This should give me a map with the marker centered on the address from db but instead I get Geocode was not successful for the following reason: INVALID_REQUEST because homeAddress is undefined.

0

1 Answer 1

1

Put the ajax request inside initMap, call the geocoder in its callback function when the address is available:

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 15,
    });

    var bounds = new google.maps.LatLngBounds();
    var geocoder = new google.maps.Geocoder();
    var markers = [];

    var oReq = new XMLHttpRequest();
    oReq.onload = function() {
      homeAddress = JSON.parse(this.responseText).address; //main field I want is address
      geocoder.geocode({
        'address': JSON.stringify(homeAddress)
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          console.log(results);
          map.setCenter(results[0].geometry.location);
          var marker = new google.maps.Marker({
            map: map,
            position: results[0].geometry.location
          });
          bounds.extend(marker.position);
          markers.push(marker);
        } else {
          alert("Geocode was not successful for the following reason: " + status);
        }
      });
    };
    oReq.open("get", "db.php", true);

    oReq.send();    
 (more logic)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.