I am trying to use Google Maps API to create an array of latitudes and longitudes (from a mySQL database of cities) that I can use as markers.
I am unsure of how to dynamically pull the cities in PHP and geocode them in javascript.
This is what I have so far. I know the geocoder line is incorrect, but I am not sure how to work it in. Any advice or solutions would be very helpful.
var geocoder = google.maps.Geocoder();
var markers = [
<?php
//orgnize fans by city
$query = "SELECT city, state, COUNT(*) fans FROM users GROUP BY city ORDER BY fans DESC";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
//pulls the city, state code from the database and stores it as a string in $address
$address = '"' . $row['city'] . ", " . $row['state'] . '"';
// "$row['city'].", ".$row['state']";
geocoder.getLatLng($address, function(point) {
$latitude = point.y;
$longitude = point.x;
});
echo "{ lat: \"".$latitude.", lng: ".$longitude.", name: "'"'.$row['city'].", ".$row['state'].'"'"},\n ";
echo "<br/>";
}
?>
];
//var locationNameArray = ['Portland','Seattle','Los Angeles','San Diego','Las Vegas'];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});
In your post you are mixing PHP with Javascript.
You can’t use a Javascript function
geocoder.getLatLnginside a PHP tag.To fill the database with lat, lng information I suggest to use the geocoding with PHP.
So you will need one table for cities.
And the user table have just a foreign key to
id_city:And here is a quick and dirty example how to get the lat, lng information from Google geocoder with PHP:
There is no error checking but I hope you get the point.
With this result you can update your database.
I hope you know how to join multiple tables to get the result from users and city tables.