PassCode PassCode -4 years ago 366
Ajax Question

Updating Location on Google Maps - API

Currently working on a small project and can't get my head around an issue I'm facing with the updating the location on a Google Map via the API.

Quick run down (This part is all working)
- Have a MySQL database with some lat and long values
- On the click of a buttonI use Ajax to hit a PHP script which pulls a random lat and long from the database and encodes to json.
- I successfully retrieve the lat and long values and can alert them or insert them anywhere on the page.

Here is where my problem is. I am using a Google Maps API snippet which works perfectly fine. It shows the map and, if I hard code a lat and long value in a function that fired at the click of a button, it re-centres the map to the new location. However, when I insert the lat and long values via the Ajax script, it doesn't update the location.

Here is my code (Only the front end jQuery. The PHP and ajax controllers work.)

<script>
var map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(48.1293954,12.556663),//Setting Initial Position
zoom: 2
});
}


function newLocation(newLat,newLng)
{
map.setCenter({
lat : newLat,
lng : newLng
});
}

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

$(document).ready(function ()
{
$("#1").on('click', function ()
{

// Get lat and long new values from MySQL
$.ajax({
type: "POST",
url: 'core/ajax_controller.php?c=controller',
data: $(this).serialize(),
dataType: 'json',
success: function(data) {

newLocation(data[0],data[1]);
map.setZoom(15);

}

});

});
});
</script>


From the example above. If I alert or print data[0], for example, which holds the lat value, it displays a value as plain text - "26.1725364". However, when adding it to the map function "newLocation" it doesn't seem to pass through to the function, and recenter the map.

However, If I remove the Ajax and just have the following, with hard coded lat and long coordinates. It works, each click of the button updates the map centre.

$("#1").on('click', function ()
{
newLocation(12.12345678,12.12345678);
map.setZoom(15);


So, it appears my problem is somehow accessing a second javascript function "newLocation" within another function.

Is there a way to do this correctly?

Thanks

Answer Source

Your data result from the Ajax request is an array of strings.

So a quick fix would be:

success: function(data) {

    newLocation(parseFloat(data[0]),parseFloat(data[1]));
    map.setZoom(15);

}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download