display google map with markers retrieved from mysql - php

i am using PHP and MYSQL in order to retrieve data from the database. i need to embed Google Map and plot markers based on the retrieved data from the MYSQL database.
i am able to retrieve data from the database and display it on the web page as an XML format. but without displaying the Google Map
where is the error in the code?
i will appreciate any help.
code :
<!DOCTYPE html>
<?php
/*
Template Name: MAP
*/
get_header();
?>
<html>
<head>
<script type='text/javascript' src='jquery-1.6.2.min.js'></script>
<script type='text/javascript' src='jquery-ui-1.8.14.custom.min.js'></script>
<style>
BODY {font-family : Verdana,Arial,Helvetica,sans-serif; color: #000000; font-size : 13px ; }
#map_canvas { width:100%; height: 100%; z-index: 0; }
</style>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=*******************&callback=initMap">
</script>
<script type='text/javascript'>
//This javascript will load when the page loads.
jQuery(document).ready( function($){
//Initialize the Google Maps
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
//Load the Map into the map_canvas div
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
//Initialize a variable that the auto-size the map to whatever you are plotting
var bounds = new google.maps.LatLngBounds();
//Initialize the encoded string
var encodedString;
//Initialize the array that will hold the contents of the split string
var stringArray = [];
//Get the value of the encoded string from the hidden input
encodedString = document.getElementById("encodedString").value;
//Split the encoded string into an array the separates each location
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
//Separate each field
addressDetails = stringArray[x].split("&&&");
//Load the lat, long data
var lat = new google.maps.LatLng(addressDetails[2], addressDetails[3]);
//Create a new marker and info window
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
//Pushing the markers into an array so that it's easier to manage them
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
global $wpdb;
//Initialize your first couple variables
$encodedString = ""; //This is the string that will hold all your location data
$x = 0; //This is a trigger to keep the string tidy
//Now we do a simple query to the database
$sql = $wpdb->get_results("select * from site_coordinates", ARRAY_N);
//Multiple rows are returned
foreach ($sql as $row)
{
//This is to keep an empty first or last line from forming, when the string is split
// if ( $x == 0 )
// {
// $separator = "";
//}
//else
//{
//Each row in the database is separated in the string by four *'s
$separator = "****";
//}
//Saving to the String, each variable is separated by three &'s
$encodedString = $encodedString.$separator.
"<p class='content'><b>Site ID :</b> ".$row[0].
"<br><b>Lat:</b> ".$row[1].
"<br><b>Long: </b>".$row[2].
"<br><b>Height: </b>".$row[3].
"<br><b>TX-Power: </b>".$row[4].
"<br><b>TX-Center: </b>".$row[5].
"<br><b>RX-Center: </b>".$row[6].
"<br><b>Coverage Area: </b>".$row[7].
"</p>";
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
</div>
<div id="map_canvas"></div>
</body>
<?php
get_footer();
?>
</html>
using echo json_encode($row);
inside the foraeach loop
this was the result :

You seem to be creating an HTML string from your DB in the PHP. Try creating the data that the googlemap JS is expecting to see, you could do this as a JSON object, easy enough to do in the PHP. Stop trying to display the DB data in HTML, instead think in JSON.
inside your foreach, try this for a start:
echo json_encode($row);
this should start to give you an idea.
then look here:
//Create a new marker and info window
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});

Related

Removing final comma from json data

I have an issue which has been causing me a headache for a few days and is probably a really simple fix for somebody with a bit more knowledge around json data than me. So hopefully somebody can help.
Firstly, I am using scriptcase, although this shouldn't matter as I am using a blank application and the only scriptcase macro I am utilising in my code is a database lookup, as you will see.
I am essentially selecting multiple fields from the database, preparing them using json to be placed inside a function for a Google Maps API (latitude and longitude, firstname and surname for description). It works perfectly, however throughout the generated array, it automatically places a comma at the end of every line. I cannot get my head around how to remove this. I have tried rtrim and trim, and neither work, but they do take the value right off of the end of the whole result, if that makes sense?
Apologies in advance if this is incredibly simple!
My code looks like this:
$LatLong = array();
$i = 0;
$llresult = '';
sc_lookup(ds,"SELECT latitude,longitude,first_name,surname FROM staff WHERE active=1");
for($i=0;$i<count({ds});$i++){
$LatLong[0][] = "var Marker = new google.maps.Marker({ position: {lat: ". {ds[$i][0]} .", lng: ". {ds[$i][1]} ."}, map: map, title: '". {ds[$i][2]} ." ". {ds[$i][3]} ."' });";
}
//include $result data
$llresult = json_encode($LatLong);
//$result treatment
$llresult = str_replace("[[","", $llresult);
$llresult = str_replace("]]","", $llresult);
$llresult = str_replace('"','', $llresult);
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Locations</title>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 90%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
function initMap() {
var myLatLng = {lat: 37.3320045, lng: -122.0329699};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: myLatLng
});
<?php echo $llresult; ?>
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
</script>
</body>
</html>
<?php
I should have added that my output upon echoing the $llresult is showing as the following:
var Marker = new google.maps.Marker({ position: {lat: 37.3320045, lng:
-122.0329699}, map: map, title: 'Joe Bloggs' });,var Marker = new google.maps.Marker({ position: {lat: 37.3320045, lng: -122.0329699},
map: map, title: 'Jane Doe' });
A simple approach that divides code and data is:
$LatLong = array();
$i = 0;
sc_lookup(ds,"SELECT latitude,longitude,first_name,surname FROM staff WHERE active=1");
for($i=0;$i<count({ds});$i++){
$LatLong[] = [
'lat' => $ds[$i][0],
'lng' => $ds[$i][1],
'title' => $ds[$i][2] . " ". $ds[$i][3]
];
}
So, now in $LatLong you will store coordinates and titles. Now, to javascript:
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: myLatLng
});
var latLong = <?php echo json_encode($LatLong)?>;
// iterate over latLong and create markers:
for (var key in latLong) {
new google.maps.Marker({
position: {lat: latLong[key]['lat'], lng: latLong[key]['lng']},
map: map,
title: latLong[key]['title']
});
}

Too much recurssion in google map

<script type='text/javascript'>
jQuery(document).ready(function($){
var geocoder;
var map;
var markersArray = [];
var infos = [];
geocoder = new google.maps.Geocoder();
var myOptions = {
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var bounds = new google.maps.LatLngBounds();
var encodedString;
var stringArray = [];
encodedString = document.getElementById("encodedString").value;
stringArray = encodedString.split("****");
var x;
for (x = 0; x < stringArray.length; x = x + 1)
{
var addressDetails = [];
var marker;
addressDetails = stringArray[x].split("&&&");
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);
marker = new google.maps.Marker({
map: map,
position: lat,
//Content is what will show up in the info window
content: addressDetails[0]
});
markersArray.push(marker);
google.maps.event.addListener( marker, 'click', function () {
closeInfos();
var info = new google.maps.InfoWindow({content: this.content});
//On click the map will load the info window
info.open(map,this);
infos[0]=info;
});
//Extends the boundaries of the map to include this new location
bounds.extend(lat);
}
//Takes all the lat, longs in the bounds variable and autosizes the map
map.fitBounds(bounds);
//Manages the info windows
function closeInfos(){
if(infos.length > 0){
infos[0].set("marker",null);
infos[0].close();
infos.length = 0;
}
}
});
</script>
</head>
<body>
<div id='input'>
<?php
$encodedString = "";
$x = 0;
$result = mysql_query("SELECT * FROM `table-name`");
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
if ( $x == 0 )
{
$separator = "";
}
else
{
$separator = "****";
}
$encodedString = $encodedString.$separator.
"<p class='content'><b>Lat:</b> ".$row[1].
"<br><b>Long:</b> ".$row[2].
"<br><b>Name: </b>".$row[3].
"<br><b>Address: </b>".$row[4].
"</p>&&&".$row[1]."&&&".$row[2];
$x = $x + 1;
}
?>
<input type="hidden" id="encodedString" name="encodedString" value="<?php echo $encodedString; ?>" />
</div>
<div id="map_canvas"></div>
I have used above code for google map location from MySQL database.
Above code fetch lat, Lang from MySQL database and dynamically create google map.
When I run above code It gave me error like that:
There are two errors named too much recursion & initMap is not function.
Can anybody help me to sort out it.
Thanks in advance.
You have not defined initMap in your js file. That's why you are getting that error. You probably need to remove the callback part from the google map api script
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" async defer></script>
To
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY" async defer></script>
Also check if the lat and lon contain valid numeric values in the following statement
var lat = new google.maps.LatLng(addressDetails[1], addressDetails[2]);

$_SESSION not passing to javascript

This is probably a simple issue but I would appreciate any help
I have loaded a $_SESSION variable from my MVC model , its a multidimensional area of latitude and longitude points in a map. here where I loaded this from
for($i=0; $i<count($markets['results']); $i++) {
.
.
$marketinfo["lat"][$i] = floatval($lat);
$marketinfo["long"][$i] = floatval($lon);
};
$_SESSION['MARKETLOCATION']['LAT'] = $marketinfo["lat"];
$_SESSION['MARKETLOCATION']['LONG'] = $marketinfo["long"];
Then down in the view section I am calling a _template for header with this code
<script type="text/javascript">
function createmap(LatLong) {
var firstpass = true;
for (var i = 0; i < $LatLong.length; i++) {
var lat = $LatLong['LAT'][i];
var lng = $LatLong['LONG'][i];
if (firstpass === true){
var map = new google.maps.Map(document.getElementById('map-canvas'),{
zoom: 10,
center: new google.maps.LatLng($lat[0]+','+$lng[0]),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
firstpass = false;
}
var infowindow = new google.maps.InfoWindow();
marker = new google.maps.Marker({
position: new google.maps.LatLng($lat[i]+','+$lng[i]),
map: map
});
}
window.onload=function(){("createmap($_SESSION['MARKETLOCATION']");};
}
</script>
</head>
<body>
<div class='Mapbox' id = 'map-canvas' ></div>
Problem is the map is not displaying at all. I know that my API key is correct because I tested it before I created this code. So I think it probibaly has to do with Passing the session variable
Again any insight would be appreciated
Javascript and php are two different languages. You need to output your variable from php but you cannot just echo it as $_SESSION['MARKETLOCATION'] is an array.
You should do something like:
var session_variable = <?php echo json_encode($_SESSION['MARKETLOCATION']); ?>;
// now you might have to do some processing on session_variable like parsing it...
// for an example:
var session_object = JSON.parse(session_variable);
window.onload=function(){ createmap(session_object); };
Fix you code:
window.onload=function(){("createmap(<?php echo $_SESSION['MARKETLOCATION'] ?>");};

Trying to make an array of latitude and longitudes dynamically in php

I am trying to make an array of latitudes and longitudes using cities that I have in a mySQL database. This is what I have so far. I am trying to set up the array variable in javascript, and echo out the fields inside. The "markers" array is read to make markers appear on the google map at the desired locations:
EDIT: Here is the entire script
<script type="text/javascript">
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
directionsDisplay.setMap(map);
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 = urlencode('"' . $row['city'] . ", " . $row['state'] . '"');
$googleApi = 'http://maps.googleapis.com/maps/api/geocode/json?address=%s&sensor=false';
$json = file_get_contents(sprintf($googleApi, $address));
$resultObject = json_decode($json);
$location = $resultObject->results[0]->geometry->location;
$lat = $location->lat;
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$lng.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
}
?>
];
// 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
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.name;
content.appendChild(title);
var streetview = document.createElement("DIV");
streetview.style.width = "200px";
streetview.style.height = "200px";
content.appendChild(streetview);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
// Handle the DOM ready event to create the StreetView panorama
// as it can only be created once the DIV inside the infowindow is loaded in the DOM.
google.maps.event.addListenerOnce(infowindow, "domready", function() {
var panorama = new google.maps.StreetViewPanorama(streetview, {
navigationControl: false,
enableCloseButton: false,
addressControl: false,
linksControl: false,
visible: true,
position: marker.getPosition()
});
});
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Your Current City'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var waypts = [];
var checkboxArray = document.getElementById('waypoints');
for (var i = 0; i < checkboxArray.length; i++) {
if (checkboxArray.options[i].selected == true) {
waypts.push({
location:checkboxArray[i].value,
stopover:true});
}
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var route = response.routes[0];
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
// For each route, display summary information.
for (var i = 0; i < route.legs.length; i++) {
var routeSegment = i + 1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += route.legs[i].start_address + ' to ';
summaryPanel.innerHTML += route.legs[i].end_address + '<br>';
summaryPanel.innerHTML += route.legs[i].distance.text + '<br><br>';
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
When I open the html, I call initialize and make the canvas:
<body onload="initialize()">
<div id="map_canvas" style="width: 1100px; height: 450px;">map div</div>
You have a typo: sometimes you use long, at other times lng.
in the code segment:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.name
});}
while earlier you use
$lng = $location->lng;
echo "{ lat: ".$lat.", lng: ".$long.", name: ".'"'.$row['city'].", ".$row['state'].'"'."},";
In effect, your echo statement, which should be producing longitudes in your array, is referencing a non-initialized variable, $long. Fix that and you should be good to go. In other words, change
$lng = $location->lng;
to
$long = $location->lng;
(or change your echo statement...)
My earlier answer dealt with the typo. I think there's a fundamental issue with "how to draw maps with the google API". The following code snippet (from google JavaScript API shows an example of using overlays (which is what a marker is):
var myLatlng = new google.maps.LatLng(-25.363882,131.044922);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP, }
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!" });
// To add the marker to the map, call setMap();
marker.setMap(map);
Several of these steps appear to be missing from your code - maybe you didn't show them, or maybe you didn't realize you needed them?
EDIT: even after you posted your full code, I still don't see certain things I would expect.
Here are one thing you can try for sure: call the google API before referencing it: add this line
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"> </script>
right below <head>, before your <script>
Fixing just this, and taking out a bunch of "superfluous" (for the purpose of "getting a map with a pin") lines, allowed me to create a simple file that can render a map of New York, NY with one marker on it. The source code can be found at http://www.floris.us/SO/maptest.php.txt . From there, you can add more stuff back in...
Further edit: with the lessons learnt, I made http://www.floris.us/SO/maptestFull.php which has most of the functionality you were looking for (not the DB lookup, which I don't have, obviously). Once again, source code is copied in .php.txt file so you can look at it. Slightly messy (from trying to turn things on/off) - you will have to look closely to see all the changes I made.

Fetch (PHP) array in (MYSQL) database and insert some php array data into JavaScript

I'm fetching an array and I would like to insert some of the data into two places in javascript but I don't know how to do it correctly, can someone please help me?
I'm fetching an array in PHP/MYSQL like so:
<?php while($row = mysql_fetch_array( $result )) { ?>
<?php
//I WANT TO LOOP THE BELOW CODE IN JAVASCRIPT SOMETHING LIKE THIS?:
echo 'var point'.$count.'= new google.maps.LatLng('.$LAT.', '.$LNG.');';
?>
<?php
// I WANT TO LOOP THIS ALSO BUT IT IS AT THE END OF THE JAVASCRIPT CODE AND THERE IS CODE IN THE MIDDLE THAT I DON'T WANT LOOPED
echo 'var marker'.$count.'= new google.maps.Marker({draggable: true,raiseOnDrag: false,icon: image,shadow: shadow,shape: shape,map: map,position: point'.$count.'});';
?>
<?php } ?>
The JavaScript looks like this:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function load(){
//** START LOOP THIS IN PHP **//
var point1 = new google.maps.LatLng(44.8041322, -93.1668858); //LOOP THIS IN PHP
//** END LOOP THIS IN PHP **//
var myMapOptions = {
zoom: 5,
center: point,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var map = new google.maps.Map(document.getElementById("map"),myMapOptions);
var image = new google.maps.MarkerImage(
'marker-images/image.png',
new google.maps.Size(40,35),
new google.maps.Point(0,0),
new google.maps.Point(20,35)
);
var shadow = new google.maps.MarkerImage(
'marker-images/shadow.png',
new google.maps.Size(62,35),
new google.maps.Point(0,0),
new google.maps.Point(20,35)
);
var shape = {
coord: [27,0,30,1,32,2,34,3,35,4,36,5,38,6,39,7,39,8,39,9,39,10,38,11,37,12,33,13,34,14,34,15,33,16,32,17,31,18,27,19,28,20,28,21,27,22,26,23,22,25,23,26,24,27,24,28,24,29,24,30,24,31,24,32,23,33,22,34,17,34,16,33,15,32,15,31,14,30,14,29,15,28,15,27,16,26,17,25,13,23,12,22,11,21,11,20,12,19,8,18,7,17,6,16,5,15,5,14,6,13,2,12,1,11,0,10,0,9,0,8,0,7,1,6,3,5,4,4,5,3,7,2,9,1,12,0,27,0],
type: 'poly'
};
//** START LOOP THIS IN PHP **//
var marker1 = new google.maps.Marker({draggable: true,raiseOnDrag: false,icon: image,shadow: shadow,shape: shape,map: map,position: point1});
//** END LOOP THIS IN PHP **//
}
</script>
I just don't know how to loop the info two times, the var point1... loop that is on top is not really a problem but how do i loop the bottom part without looping all of the javascript
The below should work, then simply insert $point_str and $marker_str in the appropriate places after the while loop.
<?php
$point_str = '';
$marker_str = '';
while($row = mysql_fetch_array( $result )) {
// define $LAT, $LNG, $count++
$point_str .= 'var point'.$count.'= new google.maps.LatLng('.$LAT.', '.$LNG.');'."\n";
$marker_str .= 'var marker'.$count.'= new google.maps.Marker({draggable: true,raiseOnDrag: false,icon: image,shadow: shadow,shape: shape,map: map,position: point'.$count.'});'."\n";
}
?>

Categories