Untitled UI logotext
Solutions
WebsitesEcommerceMobile AppsWeb AppsProduction Support & Maintenance
Our work
Company
About usBlogPodcastContact us
Book a free consultation

Getting Google Map markers from a jquery ajax call

Olivia Rhye

The Google Maps API is heavily biased to xml but what if you'd rather get your markers in json from an ajax call? Since we will be using jquery for the call you will need to include the library into your page.

First set up the code that will serve the json. We will put this at /get_markers and will be using Kohana 3 but any code will work aslong as it returns json.


//get markers from database
$lastpoints=ORM::factory('markers')->where('timestamp','>',$this->request->post('date'))->order_by('timestamp','DESC')->find_all();
if($lastpoints->count() > 0)
{
echo json_encode( array_map( create_function( '$obj', 'return $obj->as_array();'), $lastpoints->as_array() ) );
}

Now we can grab that data and use it.


$.ajax({
type: "POST",
url: '/get_markers',
dataType: 'json',
data: 'date=' + dateText,
success: function(data){
locations.length = 0;
for (p = 0; p < data.length; p++) {
locations.push(Array(data[p].latitude,data[p].longitude,data[p].timestamp));
}
initialize();
}
});

In the example above we would be reloading only the new markers onto the map. If you would like the markers to just be added to the markers that are already on the map, you will need to remove the loop and the locations length reset in the success function and just have the array push. The initialize function is the code that sets up the map and is found in most examples and tutorials on the API.

Of course you will need to set the ajax call to an event.

Ready to start a project?

Book a free consultation
Untitled UI logotext
Our work
About us
Blog
Careers
Submit a ticket
Agency Partnerships
Contact
© 2024 fjorge. All rights reserved.
Privacy