1) I have a site, using jQuery and the gMap Google Maps plugin. This all works perfectly, and I get my markers set right, and I really like this solution. This is how it looks like:
<script type="text/javascript" src="http://www.google.com/jsapi?key=MyGmapKey"></script>
<script type="text/javascript">
google.load("jquery", '1.3');
google.load("maps");
</script>
<script type="text/javascript" src="/code/js/jquery.gmap-1.1.0-min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$("#map1").gMap(
{
latitude: 48.7,
longitude: 13.4667,
zoom: 9,
markers: [{latitude: 48.461117, longitude: 13.418795, html: "MY Info Box 1"},
{latitude: 48.531602, longitude: 12.942087, html: "Another Info Box"},
{latitude: 48.198242, longitude: 13.536017, html: "Guess what? This is INFO Text!"},
{latitude: 48.325327094, longitude: 14.0712547302, html: "INFO"},
{latitude: 48.7, longitude: 13.4667,icon: { image: "images/My_Position.png", iconsize: [20, 34], iconanchor: [5, 34], infowindowanchor: [5, 2], infoshadowanchor: [14, 25] }, html: "Your current position: 48.7 | 13.4667, Germany"}],
controls: ["GSmallZoomControl3D", "GMapTypeControl"],
scrollwheel: true,
maptype: G_HYBRID_MAP,
html_prepend: '<div class="gmap_marker">',
html_append: '</div>',
icon:
{
image: "images/gmap_pin.png",
shadow: false,
iconsize: [19, 21],
shadowsize: false,
iconanchor: [4, 19],
infowindowanchor: [8, 2]
}
});
//Trailing "}" missing here...
</script>
<style type="text/css" media="screen">
#map1{ float:left; width:500px; height:500px; overflow:hidden; margin: 20px; }
.gmap_marker { font-family:Geneva, Arial, Helvetica, sans-serif; color:#0000CC; }
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div id="map1"></div>
</body>
</html>
Now my problem:
I added a "onmoveend" function, that will get new "marker" data from an external file. All works great, just the markers are not displaying right, only the LAST Item will be displayed. I'd bet it's only a small thing, but I am lost right now...
Here's what I do:
2) I added this script:
if (GBrowserIsCompatible())
{
var map = $gmap;
var center = new GLatLng(<?=$_GET['lat']?>,<?=$_GET['lon']?>);
GEvent.addListener(map, "moveend", function()
{
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
var lat = center.lat();
var lng = center.lng();
document.getElementById("lat").value = lat;
document.getElementById("lng").value = lng;
GEvent.addListener(marker, "dragend", function()
{
var point=marker.getPoint();
map.panTo(point);
var lat = point.lat();
var lng = point.lng();
document.getElementById("lat").value = lat;
document.getElementById("lng").value = lng;
});
$.getJSON('loader.php', { lat: lat, lng: lng, rad: <?=$rad?>} , function(data) {
$("#map").gMap(
{
latitude: lat,
longitude: lng,
zoom: 9,
markers: [data],
controls: ["GSmallZoomControl3D", "GMapTypeControl"], //"GScaleControl",
scrollwheel: true,
maptype: G_HYBRID_MAP,
html_prepend: '<div class="gmap_marker">',
html_append: '</div>',
icon:
{
image: "images/gmap_pin.png",
shadow: false,
iconsize: [19, 21],
shadowsize: false,
iconanchor: [4, 19],
infowindowanchor: [8, 2]
}
});
});
});
And some HTML:
<div id="map" style="float:left; width:500px; height:500px; overflow:hidden; margin: 20px;"></div>
Current coordinates: <br>
<b>Latitude:</b> <input type="text" size="34" name="latitude" value="" id="lat" /><br>
<b>Longitude:</b><input type="text" size="34" name="longitude" value="" id="lng" />
If you move the first map, I display a second map which "should" hold the new markers returned by the loader.php.
loader.php:
It's getting the new "close to me" entries from the database and then "builds" the string similar to the one used in sample 1).
Here's what it looks like:
$MyNewPositionMarker.='{latitude: '. $_GET['lat'].', longitude: '. $_GET['lng'].', html: "'.$html.'"},' ;
//Getting database results while
while($row = mysql_fetch_assoc($result))
{
$markers.='{latitude: '.$row['odin_facility_lat'].', longitude: '.$row['odin_facility_lon'].', html: "'.$html.'"},' ;
}
echo $markers.$MyNewPositionMarker
The values that are returned by loader.php "look" exactly what they should look like as per Sample 1).
I guess, my problem is to do with $.getJSON and some kind of "encode/decode" problem, but I spent all night, tried back and forth ("normal $.get"), different return formats in loader.php, but all NOT succeeding.
Right now, it looks OK, but unfortunately I just get the LAST marker set on my map. The jQuery Plugin, that is "setting" the markers can be found here: http://gmap.nurtext.de/js/jquery.gmap-1.1.0.js
(I am turning in circles and are hoping for some clarification by you guys...)
It is only a small thing in Loader.php:
echo "[".$markers.$MyNewPositionMarker."]";
//and removed the [] at the position when loading the new map: WRONG... markers: [data], ... RIGHT: ... markers: data, ...
(This is just a copy-paste of the solution in the comment to remove the question from the "unanswered" list.)
Related
I have a php code that deals with mapping markers in a google maps, and the coordinates needed are fetched from a certain data storage platform. My problem now is that the coordinates are always updating and when I run the php code it will only read the last entry of the coordinates. Is there a php function that allows a perpetual loop for the code even without opening the php code itself?
EDIT
This the php code is for the map plotter
<?
php
session_start();
require ("trial.php");
?>
<html>
<head>
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
</head>
<body>
<table><col width="500px">
<tr>
<td>
<div id="map" style="height: 500px; width: 100%;">
</div>
<script type="text/javascript">
var locations = [
['Time', <?php echo $_SESSION["latitude"]?>, <?php echo $_SESSION["longitude"]?>, 1]
];
alert(locations[6][2]);
document.write(locations[6]);
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 17,
center: new google.maps.LatLng(14.5843976,120.9762802),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
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
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
</script>
</td>
</tr>
</table>
</body>
</html>
This is the php code for the fetching
<?php
$_SESSION["longitude"] = file_get_contents("https://api.thingspeak.com/channels/Channel_ID/fields/1/last.txt");
$_SESSION["latitude"] = file_get_contents("https://api.thingspeak.com/channels/Channel_ID/fields/2/last.txt");
?>
I just have asked this question to a friend of mine. And he says I could just use a cron or cron job. And I will just research more into this function.
I am having an issue with Google Charts. I have created the exact format it shows in the example inside a PHP vaiable
['Time','Devices'],['08-12-2015 09:19:00',12],['08-12-2015 09:20:00',26],['08-12-2015 09:21:00',23],['08-12-2015 09:22:00',16],['08-12-2015 09:23:00',29],['08-12-2015 09:24:00',21],['08-12-2015 09:25:00',18],['08-12-2015 09:26:00',28],['08-12-2015 09:27:00',19],['08-12-2015 09:28:00',15],['08-12-2015 09:29:00',25],['08-12-2015 09:30:00',18],['08-12-2015 09:31:00',18],['08-12-2015 09:32:00',26],['08-12-2015 09:33:00',13],['08-12-2015 09:34:00',16],['08-12-2015 09:35:00',19],['08-12-2015 09:36:00',14],['08-12-2015 09:37:00',23],['08-12-2015 09:38:00',16],['08-12-2015 09:39:00',12],['08-12-2015 09:40:00',27],['08-12-2015 09:41:00',17],['08-12-2015 09:42:00',16],['08-12-2015 09:43:00',32],['08-12-2015 09:44:00',20],['08-12-2015 09:45:00',18],['08-12-2015 09:46:00',30],['08-12-2015 09:47:00',14],['08-12-2015 09:48:00',19],['08-12-2015 09:49:00',24],['08-12-2015 09:50:00',12],['08-12-2015 09:51:00',23],['08-12-2015 09:52:00',21],['08-12-2015 09:53:00',12],['08-12-2015 09:54:00',26],['08-12-2015 09:55:00',23],['08-12-2015 09:56:00',12],['08-12-2015 09:57:00',32],['08-12-2015 09:58:00',16],['08-12-2015 09:59:00',18],['08-12-2015 10:00:00',23],['08-12-2015 10:01:00',17],['08-12-2015 10:02:00',19],['08-12-2015 10:03:00',39],['08-12-2015 10:04:00',16],['08-12-2015 10:05:00',17],['08-12-2015 10:06:00',27],['08-12-2015 10:07:00',21],['08-12-2015 10:08:00',18],['08-12-2015 10:09:00',40],['08-12-2015 10:10:00',20],['08-12-2015 10:11:00',18],['08-12-2015 10:12:00',28],['08-12-2015 10:13:00',25],['08-12-2015 10:14:00',17],['08-12-2015 10:15:00',32],['08-12-2015 10:16:00',25],['08-12-2015 10:17:00',16],['08-12-2015 10:18:00',31]
I now want to place this inside the Chart example below but it does not work.
The variable that holds the above information is $outp. I tried to place it in but it does not work.
<html>
<head>
<script type="text/javascript"
src="https://www.google.com/jsapi?autoload={
'modules':[{
'name':'visualization',
'version':'1',
'packages':['corechart']
}]
}"></script>
<script type="text/javascript">
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
<?php echo $optp; ?>
]);
var options = {
title: 'Company Performance',
curveType: 'function',
legend: { position: 'bottom' }
};
var chart = new google.visualization.LineChart(document.getElementById('curve_chart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="curve_chart" style="width: 900px; height: 500px"></div>
</body>
</html>
If anyone can assist please, its driving me crazy.
Thanks
Rob
I am trying to create a google pie chart using ajax and php. But its not working for me. Please anyone help me. The code is given below.
My first page is piechart.php
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
function get_piechart()
{
$("#std").load("get_piechart.php");
}
</script>
<input type="button" value="piechart" onClick="get_piechart();"/>
<div id="std">
</div>
My ajax page is get_piechart.php
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(load_chart_data);
function load_chart_data() {
$.ajax({
url: 'getData1.php', // provide correct url
type: 'POST',
data: {get_chart: true},
dataType: 'JSON', // <-- since youre expecting JSON
success: function(chart_values) {
console.log(chart_values); // take a peek on the values (browser console)
draw_chart(chart_values); // call your drawing function!
}
});
}
function draw_chart(chart_values) {
var data = google.visualization.arrayToDataTable(chart_values);
var options = {
title: 'Your super chart!',
vAxis: {title: 'Hours Per Day', titleTextStyle: {italic: false}},
hAxis: {title: 'Task', titleTextStyle: {italic: false}},
};
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
data file is getData1.php
<?php
if(isset($_POST['get_chart'])) {
$values = array(
array('Task', 'Hours Per Day'),
array('Booking', 11),
array('Pending', 89),
);
echo json_encode($values);
exit;
}
?>
On clicking the piechart button i got the error Uncaught ReferenceError: google is not defined. Please help me to solve this problem
I tried to use the example given in highcharts website. But when i use it all i am getting is a blank html page. Someone please help me with the code. I do not understand why the code is not loading properly please tell me if i should add something extra to this, and please do let me know how to use a php array to make this graph work also
<html>
<head>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I believe your problem is in the order you included the scripts. Try placing jQuery first:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
Demo (working / not working).
Update: to load your data from MySQL using PHP, please see this example. However, as you pointed out yourself, encoding it using JSON might be a better option:
$data = array();
while($row = mysql_fetch_array($results)) {
$data[] = array($row[1], $row[0]);
}
echo json_encode($data);
This last echo can be used either to return the whole array using ajax (like the linked example above), or when generating the page itself (i.e. "hardcoding" it in the script):
series: [{
type: 'pie',
name: 'Browser share',
data: <?php echo json_encode($data)?>
}]
This will work since your array, when JSON encoded, can be used in place of a JavaScript literal (and the json_encode should take care of escaping everything, preventing XSS vulnerabilities).
The order of including javascripts should be:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
By this I mean, you have to include the jQuery library first before any other script.
I'm having a puzzling little problem with the Google Maps API which has had me tearing my hair out. The following code
<?php
$anim='images/animation.gif';
session_start();
if ($_SESSION['anim']==1) {
$anim='images/transparent.png';
}
//Select database
require_once('../Connections/MySQL_extranet.php');
mysql_select_db($database_MySQL_extranet, $MySQL_extranet);
// Get the hid which is passed from previous page
if (isset($_REQUEST['hid'])) {
$hid=$_REQUEST['hid'];
}
//MySQL query to select location details
$query_location = "SELECT hotel, lat, lng, zoomair, sp_lat, sp_lng FROM ex_hotel WHERE hid = '$hid'";
$location = mysql_query($query_location, $MySQL_extranet) or die(mysql_error());
$row_location = mysql_fetch_assoc($location);
//Set the session variable to pass the hotel name
$_SESSION['hotel'] = $row_location['hotel'];
?>
<!DOCTYPE html>
<!--[if IE 7 ]> <html class="ie7"> <![endif]-->
<!--[if (gt IE 7)|!(IE)]><!--> <html> <!--<![endif]-->
<!--Dump the above when IE7 users go below 2% -->
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Little Hotels - Directions to <?php echo $row_location['hotel'];?></title>
<meta name="description" content="Little Hotels provides accurate directions to hotels from any starting point you choose.">
<meta name="keywords" content="hotel directions, google maps, Little Hotels, driving directions, directions to <?php echo $row_location['hotel'];?>">
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" >
<?php
$full_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$canonical_url = strtok($full_url,'?');
echo '<link rel="canonical" href="' . $canonical_url . '" >';
?>
<link rel="stylesheet" href="css/littlehotels.css" type="text/css">
<style type="text/css">
#content{padding: 70px 5px 0; width: 100%;}
#mapcontainer{float:left; display:block;}
#mapCanvas {width: 600px; height: 400px;}
#markerStatus {height: 0px;}
#info {height: 0px;}
#infoPanel {margin-left: 620px; margin-right:10px; display:block;}
#infoPanel div {margin-bottom: 5px;}
</style>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
var lat = <?php echo $row_location['lat'];?>;
var lng = <?php echo $row_location['lng'];?>;
var latlng = new google.maps.LatLng(lat, lng);
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(startpoint) {
document.getElementById('info').innerHTML = [
startpoint.lat(),
startpoint.lng()
].join(', ');
}
function nextPage() {
saddress = document.getElementById('info').innerHTML;
location='directions_detail.php?saddr='+saddress+'&daddr='+latlng;
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var zoom = <?php echo $row_location['zoomair'];?>;
var sp_lat = <?php echo $row_location['sp_lat'];?>;
var sp_lng = <?php echo $row_location['sp_lng'];?>;
var startpoint = new google.maps.LatLng(sp_lat, sp_lng);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: zoom,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
streetViewControl: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
});
var destimage = new google.maps.MarkerImage('/images/hotel_icon.gif',
new google.maps.Size(32, 37),
new google.maps.Point(0,0),
new google.maps.Point(16, 35));
var destshadow = new google.maps.MarkerImage('/images/hotelshadow.png',
new google.maps.Size(51, 37),
new google.maps.Point(0,0),
new google.maps.Point(16, 35));
var marker = new google.maps.Marker({
icon: destimage,
shadow: destshadow,
map: map,
position: latlng
});
var startimage = new google.maps.MarkerImage(
'/images/start_icon.png',
new google.maps.Size(59, 37),
new google.maps.Point(0,0),
new google.maps.Point(29, 35));
var marker = new google.maps.Marker({
position: startpoint,
title: 'If necessary, drag this to a different start point',
map: map,
draggable: true,
icon: startimage
});
// Update current position info.
updateMarkerPosition(startpoint);
geocodePosition(startpoint);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body onload="initialize()">
<div id="wrapper">
<img src="images/transparent.png" width="266" height="122" border="0" alt="Little Hotels">
<img src="<?php echo $anim ?>" alt="Little Hotels logo" width="93" height="117" align="top">
<img src="images/header/directions.png" alt="Little Hotels" width="364" height="88">
<div id="container">
<?php include("includes/topnavbar.html"); ?>
<div id="breadcrumb">
<div class="bc-link" style="width:200px">Car Hire at competitive rates</div>
<div class="bc-link">Flights</div>
<div class="bc-link">Ferries</div>
<div class="bc-link">Airport Parking</div>
<div class="bc-link">Airport Hotels</div>
<div class="bc-link" style="width:200px">Travel Insurance</div>
<div class="bc-link" style="width:200px" align="right">News and Special Offers</div>
</div>
<div id="content">
<div id="mapcontainer">
<table border=1 bordercolor="#666666">
<tr>
<td>
<div id="mapCanvas"></div>
</td>
</tr>
</table>
</div>
<div id="infoPanel">
<h2>Driving Directions to <?php echo $row_location['hotel'];?> </h2>
<!-- Following two lines must be kept in, even though not visible. Also corresponding lines in Style -->
<div id="markerStatus" style="visibility:hidden;"><i>Click and drag the marker.</i></div>
<div id="info" style="visibility:hidden;"></div>
<b>Start Point:</b>
<div id="address"></div>
<br><b>Destination:</b><br>
<div><?php echo $row_location['hotel'];?></div>
<br>
To select a different starting point, just drag the start icon to the required location (zoom in if necessary for better precision).<br>
<br>
<button onclick="nextPage()">Get Directions</button>
<br>
<span class="verdana"><br>
</span>
</div>
</div>
</div>
</div>
</body>
</html>
<?php
$_SESSION['anim']=1;
?>
creates a satisfactory page (http://new.littlehotels.co.uk/directions_hotel.php?hid=colorado) but I want to add a couple of refinements. These changes need me to create a javascript variable from a piece of MySQL data.
Therefore I want to create a line something like this:
var hotelname = <?php echo $row_location['hotel'];?>;
That shouldn't be too hard as I already have several similar lines in the working code. However, this new line breaks the page every time, no matter what variations I try. When I add that line in, the page displays but without the map and without the name of the Start Point on the righthand side.
Is it me?????????????
I am guessing you are outputting a string from $row_location['hotel'] in that case you need to wrap in quotes to tell javascript its not a variable but a string value.
thus:
var hotelname = "<?php echo $row_location['hotel'];?>";
To check if the above hypothesis is true check your console and you will see the following error:
ReferenceError: <value returned by $raw_location['hotel']> is not defined
Like this one can pass variables to JS and it prevents the PHP interpreter from complaining about any missing indexes, just in case (it depends how error reporting is set in php.ini), for example:
var hotelname = "<?php echo(isset($row_location['hotel']) ? $row_location['hotel'] :''); ?>";
console.info(hotelname);
The surrounding quotes are the difference, like this $row_location['hotel'] gets casted to string in JavaScript.
... what does this code return, you even get any result?
while ($row_location = mysql_fetch_assoc($location)) {
echo '<pre>'.print_r($row_location,true).'</pre>';
}