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']
});
}
Related
i am using PHP & MYSQL on wordpress in order to retrieve data from the database that contains coordinates and display markers on the Google Map.
Markers are shown on the map with the info window contains the coordinates.
i want to retrieve more info from the database and includes it in the info window
in the debug mode it show the info that is i want to add to the info window when i uncomment it markers will not show.
code:
<?php
/*
Template Name: MAP2
*/
get_header();
?>
<!DOCTYPE html>
<html>
<head>
<title>Custom Markers</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=********&callback=initMap">
</script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 600px;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map,currentPopup;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: new google.maps.LatLng(33.888630, 35.495480),
mapTypeId: 'roadmap'
});
var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
var icons = {
parking: {
icon: iconBase + 'parking_lot_maps.png'
},
library: {
icon: iconBase + 'library_maps.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
function addMarker(feature) {
var marker = new google.maps.Marker({
position: feature.position,
// i need to add here the info
//icon: icons[feature.type].icon,
map: map
});
var popup = new google.maps.InfoWindow({
content: feature.position.toString(),
//or here the info
maxWidth: 300
});
google.maps.event.addListener(marker, "click", function() {
if (currentPopup != null) {
currentPopup.close();
currentPopup = null;
}
popup.open(map, marker);
currentPopup = popup;
});
google.maps.event.addListener(popup, "closeclick", function() {
map.panTo(center);
currentPopup = null;
});
}
var features = [
<?php
global $wpdb;
$prependStr ="";
foreach( $wpdb->get_results("SELECT siteID, latitude, longitude FROM site_coordinates2", OBJECT) as $key => $row) {
$latitude = $row->latitude;
$longitude = $row->longitude;
$info = $row->siteID;
echo $prependStr;
?>
{
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
// info:<?php echo $info;?>,
}
<?php
$prependStr =",";
}
?>
];
for (var i = 0, feature; feature = features[i]; i++) {
addMarker(feature);
}
}
</script>
</body>
</html>
<?php
get_footer();
?>
where the AM001 is the first Site ID in the MYSQL databases
assuming that you want us sietID as info
var features = [
<?php
global $wpdb;
$prependStr ="";
foreach( $wpdb->get_results("SELECT siteID, latitude, longitude FROM site_coordinates2", OBJECT) as $key => $row) {
$latitude = $row->latitude;
$longitude = $row->longitude;
$info = $row->siteID;
echo $prependStr;
?>
{
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php echo $longitude; ?>),
info:<?php echo $info;?>,
}
<?php
$prependStr =",";
}
?>
];
then in your var popup you should add the info text
var popup = new google.maps.InfoWindow({
content: feature.position.toString() + ' my info siteID: ' + feature.info ,
//or here the info
maxWidth: 300
});
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]
});
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'] ?>");};
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.
I would like to display over 100 locations each with detailed bubble contents (ie Company Name, Address, Phone Number, Website, Industry) on a custom Google Map. How can I fetch these locations from a MySQL database using Google Maps API 3 and PHP?
say you have an sql database of this type:
id/lat/lon/comment
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key= **your key** &sensor=true">
</script>
$sqlprep = "SELECT * FROM table_name";
$doselect = mysql_query($sqlprep);
echo "<script> var locations = [";
while ($loc = mysql_fetch_assoc($doselect)){
echo "['" .$loc[comment] ."', " . $loc['lat'] . ", " . $loc['lon'] . "";
}
echo " ];</script>";
and then in your java:
<script>jQuery(window).ready(function(){
function initialize() {
var myLatlng = new google.maps.LatLng( YOUR CENTER LAT,LAN HERE );
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var infowindow = new google.maps.InfoWindow()
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
//adding the pop up windows here:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
initialize() ;
}); </script>
your html should be something like:
<html>
<body >
<div id="map_canvas" >
</div>
</body>
</html>
i might be missing some parentheses but you get the point ;)
hope it helps even 8 months later :)