Radon
Radon

Reputation: 21

Showing a map, while retrieving coordinates from a db through ajax/php

I have to retrieve coordinates for a specific place from a db and then show a map centered on them.. My solution seems not working because it tries to open a map without coordinates

function readyf() {
var map;
var info;
var lat;
var lon;

function initialize() {

    $.ajax({
        method: "POST",
        //dataType: "json", //type of data
        crossDomain: true, //localhost purposes
        url: "getLocation.php", //Relative or absolute path to file.php file
        //data: {order: ordering},
        success: function (response) {
            console.log(response);
            info = JSON.parse(response);

            lat = info[0].lat;
            lon = info[0].lon;
            console.log(lat);

        },
        error: function (request, error) {
            console.log("Error");
        }
    });

    console.log(lat);

    var mapOptions = {
        zoom: 8,
        center: new google.maps.LatLng(lat, lon)
    };
    map = new google.maps.Map(document.getElementById('map-canvas'),
        mapOptions);
}

google.maps.event.addDomListener(window, 'load', initialize);

}

Upvotes: 1

Views: 289

Answers (1)

SpenserJ
SpenserJ

Reputation: 802

You need to move the map initialization into your success callback. Otherwise the AJAX request begins, the map is initialized, and then your success callback fires off with the coordinates.

function readyf() {
    var map;
    var info;
    var lat;
    var lon;

    function initialize() {

        $.ajax({
            method: "POST",
            //dataType: "json", //type of data
            crossDomain: true, //localhost purposes
            url: "getLocation.php", //Relative or absolute path to file.php file
            //data: {order: ordering},
            success: function (response) {
                console.log(response);
                info = JSON.parse(response);

                lat = info[0].lat;
                lon = info[0].lon;
                console.log(lat);

                var mapOptions = {
                    zoom: 8,
                    center: new google.maps.LatLng(lat, lon)
                };
                map = new google.maps.Map(document.getElementById('map-canvas'),
            mapOptions);

            },
            error: function (request, error) {
                console.log("Error");
            }
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);
}

Upvotes: 1

Related Questions