i am working on tracking a vehicle. I am trying to update my map marker when i do change in my database. I do the following code that show marker but i need it to update while change the location value in MYSQL database
My code is here
<?php
include('connect.php');
if(!isset($_POST['bus_select'])){
header('Location: index.php');
exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>JU Bus Google Map</title>
<style type="text/css">
html {height:100%}
body {height:100%;margin:0;padding:0}
#googleMap {height:100%}
</style>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCzr1ZAuglRaD5BQA2u03fWftMB7RkOzxE&sensor=false"></script>
<?php
//for important date page
function value_return($query){
$result= mysql_query($query);
$value=mysql_result($result,0);
return $value;
}
$lat= value_return('SELECT `lat` FROM `bus` WHERE `bus_id`='.$_POST['bus_select']);
$long= value_return('SELECT `long` FROM `bus` WHERE `bus_id`='.$_POST['bus_select']);
$detail= value_return('SELECT `bus_details` FROM `bus` WHERE `bus_id`='.$_POST['bus_select']);
$last_updated= value_return('SELECT `last_update` FROM `bus` WHERE `bus_id`='.$_POST['bus_select']);
print '
<script>
var myCenter=new google.maps.LatLng('.$lat.','.$long.');
var marker;
function initialize()
{
var mapProp = {
center:myCenter,
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
marker=new google.maps.Marker({
position:myCenter,
animation:google.maps.Animation.BOUNCE
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content:"'.$detail.'<br>Last Updated: '.$last_updated.'"
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, "load", initialize);
</script>';
?>
</head>
<body>
<div id="googleMap" ></div>
</body>
</html>
You need to requery the database - usually done with AJAX...here is a tutorial example.
After that you simply call marker.setPosition(YOUR-NEW-LATLNG)
Related
I have a problem trying to use Google Maps API in my code.
The problem is that with my code and my API KEY without restrictions, I get an ERROR: OVER_QUERY_LIMIT error.Althought if I put restrictions to my API KEY(localhost,https://localhost,https://localhost:80....)I have an ERROR: REQUEST_DENIED.
function geocode($address){
// url encode the address
$address = urlencode($address);
// google map geocode api url
$url = "https://maps.googleapis.com/maps/api/geocode/json?address=
{$address}&key=AIzaSyDZaPEOrHX1Xd0VfiX2aV2xfn7_XeHiSls";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// response status will be 'OK', if able to geocode given address
if($resp['status']=='OK'){
// get the important data
$lati = isset($resp['results'][0]['geometry']['location']['lat']) ?
$resp['results'][0]['geometry']['location']['lat'] : "";
$longi = isset($resp['results'][0]['geometry']['location']['lng']) ?
$resp['results'][0]['geometry']['location']['lng'] : "";
$formatted_address = isset($resp['results'][0]['formatted_address'])
? $resp['results'][0]['formatted_address'] : "";
// verify if data is complete
if($lati && $longi && $formatted_address){
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi,
$formatted_address
);
return $data_arr;
}else{
return false;
}
}
else{
echo "<strong>ERROR: {$resp['status']}</strong>";
return false;
}
}
?>
<!-- google map will be shown here -->
<div id="gmap_canvas">Loading map...</div>
<div id='map-label'>Map shows approximate location.</div>
<!-- JavaScript to show google map -->
<script type="text/javascript" src="https://maps.google.com/maps/api/js?
key=AIzaSyDZaPEOrHX1Xd0VfiX2aV2xfn7_XeHiSls"></script>
<script type="text/javascript">
function init_map() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(<?php echo $latitude; ?>, <?
php echo $longitude; ?>),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new
google.maps.Map(document.getElementById("gmap_canvas"),
myOptions);
marker = new google.maps.Marker({ map: map,
position: new google.maps.LatLng(<?php echo $latitude; ?>, <?php
echo $longitude; ?>)
});
infowindow = new google.maps.InfoWindow({
content: "<?php echo $formatted_address; ?>"
});
google.maps.event.addListener(marker, "click", function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
<?php
I would like to know how I could load the coordinates (longitude and latitude) of my database in real time without updating the page even if there will be changes in the database.
I used setInterval (function ()) to reload data but still get the same coordinates.
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=fma120;charset=utf8', 'root', '');
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('SELECT latitude,longitude FROM gps_data ORDER BY id DESC LIMIT 1 ');
$donnees = $reponse->fetch() ;
?>
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap() {
var uluru = {lat:<?php echo $donnees['latitude'] ;?> , lng: <?php echo $donnees['longitude'] ;?>
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
setInterval(function(){ initMap() }, 3000);
</script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyADJopukImlmQs73l4o3xdddlcg_OBj1vaqB8&callback=initMap">
</script>
</body>
</html>
I explain:
my script loads the map (the last id = 1) .. after I add another column in the database (with id = 2), I would like the script to load the last column (id = 2) without updating the page
Please help me
Trying a new method of plotting a marker on google map with my lat/long queried from a data base. when i create variables within the jquery script tag, it works but im not able to make a call outside out that script. But when i try to set those variables with a json_encode from the php array outside of that script, the console returns with
Uncaught SyntaxError: Unexpected token < index:html:29
<!DOCTYPE html>
<html>
<head>
<style>
#map {
width: 1200px;
height: 900px;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script src="http://code.jquery.com/jquery-1.11.3.min.js">></script>
<script type = "text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(38.4403, -122.5463);
var mapOptions = {
zoom: 10,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker.setMap(map);
}
var latitude = <?php echo json_encode($lat);?>;
var longitude = <?php echo json_encode($long);?>;
var LatLong = new google.maps.LatLng(latitude, longitude);
var marker1 = new google.maps.Marker({
position: LatLong;
title:"Test"
});
marker1.setMap(map);
</script>
</head>
<body onload = "initialize()">
<div id="map"></div>
</body>
</html>
PHP to query over database:
<?php
require("server_info.php");
$connection=db2_connect($database, $username, $password);
if (!$connection) { die('Not connected : ' . db2_conn_error());}
$query = "SELECT lat,long FROM SCHOOL";
$stmt = db2_prepare($connection, $query);
$result = db2_execute($stmt);
$lat = array();
$long = array();
while ($row = db2_fetch_array($stmt)) {
$lat = $row[0];
$long = $row[1];
}
//echo json_encode($lat);
//echo json_encode($long);
db2_close($connection);
?>
The problem is that your file is named index.html. By default, only files with .php suffix are executed using PHP. Since it has a .html extension, the webserver is just returning the file verbatim to the browser, instead of running it through PHP, so <?php echo json_encode($lat); ?> is sent to the client, and that's not valid Javascript.
You should rename it to index.php, then it will be executed using PHP, and the variables will be substituted.
But it looks like there's more to the problem than this. You never set the variables $lat and $long anywhere in the script. You're setting them in a completely different script.
What you probably should be doing is using AJAX to call the query script from Javascript.
I am trying to build a website that displays a google map with a user location (lat/long) from a php service that I wrote.
I already have a php script that gets the lat/long from a mobile app (via POST from the client), stores it in a DB, and read it back from the DB into two variables, let's call them $lat and $long. To make sure I have the right values in $lat and $long, I did a simple echo and got the two values.
I am struggling with understanding how to read these values from my index.html script. All the examples that I have seen suggest keeping the php code in the html file but I would rather keep them separate. I am also not sure how to assign these values to parameters in HTML/Javacript so I can actually display them on the map.
So my questions are:
1. how do I call that php file from HTML?
2. and how do I read $lat and $long from the php service and assign them to parameters in HTML/Javascript that I can display on the map?
EDIT: here is my PHP code and my index.html (Which is a 1:1 copy from the Google Maps v3 docs).
location.php:
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
$lat = $post_data['lat'];
$long = $post_data['long'];
//CONNECT TO MYSQL
$con1 = mysql_connect("localhost", "francesco", "bbbbbb", "location111");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysql_select_db('location111');
if(mysql_select_db('location111')) { echo 'true '; } else { echo 'falise'; }
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
if (!empty($lat)) {
$sql = "INSERT INTO LocationInfo (latitude, longitude)
VALUES ('$lat', '$long');";
mysql_query($sql) or die ('Error updating database: ' . mysql_error());
}
$read_query = "SELECT * FROM LocationInfo;";
$results = mysql_query($read_query) or die ('Error reading from database: ' . mysql_error());
$column = array();
while($row = mysql_fetch_array($results)){
$column[] = $row;
}
$current_lat = $column[sizeof($column) - 1]['latitude'];
$current_long = $column[sizeof($column) - 1]['longitude'];
echo $current_lat;
echo $current_long;
?>
index.html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>My GeoLocation</title>
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<script>
var map;
function initialize() {
// var myLatlng = new google.maps.LatLng(40.7127840,-74.0059410);
var mapOptions = {
zoom: 14
//mapTypeId: google.maps.MapTypeId.ROADMAP
//center: myLatlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
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: 'Location found using HTML5.'
});
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);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
First of all, if you want to display something in template with php, it must have .php extension, not .html
You can then use your php inside of inline javascript like that:
<script type="text/javascript">
var long = "<?php echo $long;?>";
var lat= "<?php echo $lat;?>";
</script>
Or you can use Ajax on other hand
Hi i am using the javascript code below to display google maps inside a show/hide div.
PS I want the map be hidden by default when the page loads. so i wrote this:
<script type="text/javascript">
// <![CDATA[
function showlayer(layer) {
var mymap = document.getElementById(layer).style.display;
if (mymap == "block") {
document.getElementById(layer).style.display = "none";
} else {
document.getElementById(layer).style.display = "block";
}
}
// ]]>
</script>
<div id="mymap" style="display:none;">
<? include $this->loadTemplate( 'map.php' ); ?>
</div>
the map.php file contains the code below:
<script src="http://maps.googleapis.com/maps/api/js?v=3.6&sensor=false" type="text/javascript"></script>
<script type="text/javascript">
function initialize() {
var mapLatlng = new google.maps.LatLng(<?php echo $this->link->lat . ', ' . $this->link->lng; ?>);
var mapOptions = {
zoom: <?php echo ($this->link->zoom?$this->link->zoom:13); ?>,
center: mapLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
var marker = new google.maps.Marker({
position: mapLatlng,
map: map,
title:"<?php echo addslashes($this->link->link_name); ?>"
});
}
jQuery(document).ready(function(){initialize();});
</script>
When i remove the style="display:none; everything works ok but i dont want to display the map on page load.
Any help ??
Call initialize after you do document.getElementById(layer).style.display = "block"; because there is a bug I think that does not center the maps correctly in the specified lat and long. So load the map, after the div is shown.