samedi 25 avril 2015

How To Add Google Map Markers From Mysql Database Only Using Address With Geocoder


I am trying to create some code that pulls an address from a mysql database with JSON. This works. However I cant finish the script that pulls the JSON array and adds markers to a google map with the Geocoder API. Please note this should work without lat and lon; it adds markers purely with just an address

Here is the code for the JSON mysql array:

require 'config.php';

try {

    $db = new PDO($dsn, $username, $password);
    $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

    $sth = $db->query("SELECT * FROM peopleforjobs");
    $locations = $sth->fetchAll();

    echo json_encode( $locations );

} catch (Exception $e) {
    echo $e->getMessage();
}

And here is the javascript on the main page where the map is shown:

  function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
    request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
    request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
    if (request.readyState == 4 && request.status == 200) {
        callback(request);
    }
}
request.open("GET", url, true);
request.send();
}
var map;

// Ban Jelačić Square - City Center
var center = new google.maps.LatLng(45.812897, 15.97706);

var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();

function init() {

var mapOptions = {
  zoom: 13,
  center: center,
  mapTypeId: google.maps.MapTypeId.ROADMAP
}

map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

makeRequest('get_locations.php', function(data) {

    var data = JSON.parse(data.responseText);

    for (var i = 0; i < data.length; i++) {
        displayLocation(data[i]);
    }
});
}

if (geocoder) {
geocoder.geocode({
  'address': location.address
}, function(results, status) {
  if (status == google.maps.GeocoderStatus.OK) {
    if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {
      map.setCenter(results[0].geometry.location);

      var infowindow = new google.maps.InfoWindow({
        content: '<b>' + location.address + '</b>',
        size: new google.maps.Size(150, 50)
      });

      var marker = new google.maps.Marker({
        position: results[0].geometry.location,
        map: map,
        title: location.address
      });
      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });

    } else {
      alert("No results found");
    }
  } else {
    alert("Geocode was not successful for the following reason: " + status);
  }
 });
}

It Throws An Error: "ZERO_RESULTS" Does anybody know why?


Aucun commentaire:

Enregistrer un commentaire