Skip to content Skip to sidebar Skip to footer

Google Maps Markers With Javascript And PHP

I am building an application that has a database of people's names, info about them and their current location. I managed to create a maps using Google maps javascript API, and ma

Solution 1:

It would be better to json_encode your data, pass that to a variable in javascript, and then loop over it using javascript. Even better would be using AJAX requests to fetch the data.

<?php
function fetchGigs() {
  $gigs = new Array();
  $query = mysql_query("SELECT * FROM gigs");
  while($gig = mysql_fetch_array($query)) {
    $gigs[] = $gig; 
  }
  return $gigs;
}

And in your javascript:

<script>
// your other code...
var gigs = <?php echo json_encode(fetchGigs()); ?>

var createMarkerAt = function(lat, lng) {
  var latLng, marker;
  latLng = new google.maps.LatLng(lat, lng);
  marker = new google.maps.Marker({
    position: latLng,
    map: map,
  });
  return marker;
}

var createMarkerForGig = function (gig) {
  var marker, info;
  marker = createMarkerAt(gig.lat, gig.lng);
  info = new google.maps.InfoWindow({
    content: 'Name: <b>"' + gig.name + '"</b><br>Info: <b>"' + gig.desc + '"</b>'
  });
  google.maps.event.addListener(marker, 'click', function() {
    info.open(map, marker);
  });
  return marker;
}

// Add markers for all the gigs.
var len = gigs.length;
for (var i = 0; i<len; i++) {
  createMarkerForGig(gigs[i]);
}
</script>

Documentation for php_encode()


Solution 2:

When I wrote a similar application I used php to write the string of a javascript array representing my data and then used straight js once i got to building strings for the api. However, since I have discovered how easy it is to write a PHP powered API to return JSON objects of my database I just use jQuery to query my homebrew API for the json data and then work with that. It truly is incredibly easy to do with SLIM. Here is a link http://codingthis.com/programming/php/using-the-slim-php-framework-for-developing-rest-apis/


Post a Comment for "Google Maps Markers With Javascript And PHP"