I’m trying to use the Google Maps V3 API to create markers on a google map. I have the coordinates of the markers in mySQL database, and is currently in a PHP array in my .php file. Now how do I use a foreach() loop (or another suitable method) to loop through the elements in my PHP array and create a new google map marker with each iteration of the loop?
PS: My PHP is decent, but not my javscript knowledge. The tutorial I’m following now on creating the markers is at http://www.svennerberg.com/2009/07/google-maps-api-3-markers/
Code
I’m using Codeigniter framework, so the controller+model file already retrieved the necessary data(name, lng, lat…) into an array $map. I can loop the array using the usual method:
foreach($map as $row) {
$lng = $row[lng] // this is not necessary, its just to show what is in the array
$lat = $row[lat]
// now how do I use this loop to create new marker code in javascript?
}
The JS code for creating a google map marker which has to be created once per foreach loop iteration is like:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng($lng, $lat), // how do i pass the PHP variables into the JS code?
mapTypeId: google.maps.MapTypeId.ROADMAP
});
So my question is how do i pass the PHP variables in the PHP array to create the JS code above, once per each foreach() loop iteration?
First of all, you are on the right track, but you just need to understand the separate concepts of server-side and client-side languages and how they can interact. PHP doesn’t “pass” variables to JavaScript, but what it does do is generate whatever HTML document you want.
That HTML document then can contain JavaScript, which will execute as the page is rendered by the browser. So, think of your PHP as making the JavaScript code:
Example of PHP outputting JavaScript code in HTML page:
Now, I looked up the tutorial, and actually the code in your question is not the right code — instead it is the code to create the map, and the lat/long parameters in your example are for the center, not a marker.
So, in your PHP page, you want to do the following:
var map = new google.maps.Map...(as shown in the tutorial)$maparray with array items containing the'lng'and'lat'keys. (Note: you should always wrap array key names with quotes)<?phpto create a PHP code block, and create yourforeachloop. For each item, create the JavaScript code needed to create the marker.Example of foreach loop: