I am super new to web development and building a web app that has a google map and would like to continuously update the map with the user location. I am able to read values from my db properly and can display it on the map, but only one time. I could not find anywhere how to continuously update the position (hopefully without reloading the page also). Can someone help with some direction on how to approach this? Here some of my code for reference:
<?php include_once('location.php') ?>
<!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(<?php echo $current_lat ?>, <?php echo $current_long ?>);
var mapOptions = {
zoom: 14,
center: myLatlng
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'TEST'
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
</html>
//READ FROM CLIENT (POST)
$content = file_get_contents('php://input');
$post_data = json_decode($content , true);
$lat = $post_data['lat'];
$long = $post_data['long'];
$speed = $post_data['speed'];
$hacc = $post_data['hacc'];
$vacc = $post_data['vacc'];
$timestamp = $post_data['timestampe'];
//CONNECT TO MYSQL
$con1 = mysql_connect("localhost", "xxxxxxxx", "bbbbbb", "yyyyyy");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$db_selected = mysql_select_db('yyyyyy');
if (!$db_selected) {
die ('Can\'t use foo : ' . mysql_error());
}
if (!empty($lat)) {
$sql = "INSERT INTO LocationInfo (latitude, longitude, speed, hor_acc, ver_acc, d)
VALUES ('$lat', '$long', '$speed', '$hacc', '$vacc', '$timestamp');";
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'];
?>
Google Maps JavaScript reference
You can update the marker with marker.setPosition( new LatLng(...) ), or in other words just assigning a new position. It seems to me you're putting your position in an input field, than submitting, reading the field and setting the marker and saving the position in a database. If you want to update the position of the marker, you can use an input field again, read the field value with JavaScript, and update the marker's position (with marker.setPosition()). If you want to pass this to your DB again, you can additionally pass the data to your script using AJAX. It depends on what you're doing and want you want to do.
edited after comment
You can setup a JavaScript function that will make an AJAX request to your PHP script and update the position once it gets the data. And then call the script every x number of seconds. use setTimeout to create a delay and then make the function call itself with another timeout once it gets the data. Save yourself the trouble and use a library to handle your AJAX calls - jQuery gives you indirectly a lot of support because a lot of people use it. You also need to make sure your PHP script doesn't give you anything back except the position information, not the whole html file as you have now. So simplified something like this: you have a PHP file that sends you the lat/lng pair as JSON, and this script gets called from the browser around every 10 seconds. There are ofcourse little things that might pop out ... and please note, I don't do PHP.
get_position.php
...
$latLng = array('lat' => $lat, 'lng' => $lng);
echo json_encode($latLng);
JS, using jQuery.ajax
var marker = ....
var delay = 10000; // 10 second delay
function updatePosition() {
$.ajax({
url: path/to/get_position.php,
dataType: 'json'
})
.done(function callDone(data) {
// update marker position
var latLng = new google.maps.LatLng( data.lat, data.lng );
marker.setPosition( latLng );
// call the function again
setTimeout( updatePosition, delay );
});
}
// call the function initally
setTimeout( updatePosition, delay );
Related
I have 2 pieces of working code. This first is slightly convoluted but it brings me back the location I need.
<?php
$ider = $_GET['id'];
$host = "localhost";
$user = "Meh";
$password ="pass";
$database = "MyDB";
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// connect to mysql database
try{
$connect = mysqli_connect($host, $user, $password, $database);
} catch (mysqli_sql_exception $ex) {
echo 'Error';
}
$sql = "SELECT id, Location FROM MyDB WHERE id =$ider";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$thisloc = $row["Location"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Now I want to use this info on a lil google api javascript boyo with multiple markers.
<html>
<head>
<title>Custom Markers</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<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%;
width: 70%
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(
document.getElementById('map'),
{center: new google.maps.LatLng(62.009094, -7.316163), zoom: 13});
var iconBase =
'https://developers.google.com/maps/documentation/javascript/examples/full/images/';
var iconBase2 =
'http://icons.iconarchive.com/icons/paomedia/small-n-flat/32/';
var icons = {
equipment: {
icon: 'http://icons.iconarchive.com/icons/icons-land/vista-map-markers/32/Map-Marker-Marker-Outside-Azure-icon.png'
},
library: {
icon: iconBase2 + 'map-marker-icon.png'
},
info: {
icon: iconBase + 'info-i_maps.png'
}
};
var dormant = 'equipment';
var active = 'library';
var later = 62.013376;
var longer = -7.307036;
var features = [
{
position: new google.maps.LatLng(62.018596, -7.292223),
type: dormant
}, {
position: new google.maps.LatLng(62.013376, -7.307036),
type: dormant
}, {
position: new google.maps.LatLng(62.009094, -7.316163),
type: dormant
}, {
position: new google.maps.LatLng(62.990540, -7.318134),
type: dormant
}, {
position: new google.maps.LatLng(62.005287, -7.309028),
type: dormant
}, {
position: new google.maps.LatLng(later, longer),
type: active
}
];
// Create markers.
for (var i = 0; i < features.length; i++) {
var marker = new google.maps.Marker({
position: features[i].position,
icon: icons[features[i].type].icon,
map: map
});
};
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap"> >
</script>
</body>
</html>
As you can see i'm not a very sophisticated programmer. More of a junkyard dog.
There's a lot going on there - but I'm in the middle of a few changes and I need the info for testing.
Both scripts just won't seem to work together, page cannot be displayed. Am I going about this the right way? Any advice would be great.
if database has Names of places instead of coordination try Using this API instead
https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=<?php echo$thisloc;?>&inputtype=textquery&fields=photos,formatted_address,name,geometry&key=YOUR_API_KEY
After taking the advice of #Rkv88 - Kanyan and a long day of troubleshooting, I managed to isolate the problem. It was actually the PHP. Weirdly when I echoed a result it would display the output, but with no echo it caused - Page cannot be displayed.
Anyways
I just rewrote the PHP script to what I needed. It's probably not the most sophisticated thing in the world. But I only need a specific value every time
<?php
$ider = $_GET['id'];
$conn = mysqli_connect("localhost", "meh", "pass", "MyDB");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT Location FROM LifeSaver1 WHERE id =$ider";
$result = $conn->query($sql);
$obj = mysqli_fetch_object($result);
$obj2 = $obj->Location;
?>
i have try to fetch lat and long value from mysql db and pass those value on google map for show location marker on map
but currently i have fetch only last rows data so indicate marker only one place
how to display all location on map??
<?php
include "config.php";
$result="select * from ds_duty_history";
$a=mysqli_query($conn,$result);
// $count_row = mysqli_num_rows($a);
while ($b = mysqli_fetch_array($a)) {
$long_d=$b['lng'];
$lat_d=$b['lat'];
$result = array(array('latitude'=>$lat_d,'longitude'=>$long_d));
}
?>
<!doctype html>
<html>
<head>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOURKEY&callback=initMap">
</script>
<script type="text/javascript">
var map;
function initialize() {
// Set static latitude, longitude value
var latlng = new google.maps.LatLng(<?php echo $lat_d; ?>, <?php echo $long_d; ?>);
// Set map options
var myOptions = {
zoom: 16,
center: latlng,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Create map object with options
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<?php
// uncomment the 2 lines below to get real data from the db
// $result = mysql_query("SELECT * FROM parkings");
// while ($row = mysql_fetch_array($result))
foreach($result as $row){ // <- remove this line
echo "addMarker(new google.maps.LatLng(".$row['latitude'].", ".$row['longitude']."), map);";}
?>
}
function addMarker(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
});
return marker;
}
</script>
</head>
<body onload="initialize()">
<div style="float:left; position:relative; width:550px; border:0px #000 solid;">
<div id="map_canvas" style="width:550px;height:400px;border:solid black 1px;"></div>
</div>
</body>
</html>
currently display only one marker i.e last fetch record lat and long assign on map
how to display all place on map using mysql lat,long value?
The main problem you have here is that you're not actually collecting different results in your $result variable but overwrite it with the most recent one. The also seems to be some abuse of the variable $result which might be contributing to your confusion. Let's say we declare a new array and call it $rows. Then we can collect all the rows with the following code (to substitute your first snippet):
<?php
include "config.php";
$sql = "SELECT * FROM ds_duty_history";
$result = mysqli_query($conn, $sql);
$rows = [];
while ($row = mysqli_fetch_array($result)) {
$lon_d = $row['lng'];
$lat_d = $row['lat'];
// Use short-cut append syntax here so we add row and don't overwrite $rows
$rows[] = ['latitude' => $lat_d, 'longitude' => $long_d];
}
?>
Now in your display code (the second snippet) you would be able to iterate over $rows pretty much like:
foreach ($rows as $row){
// Do work with each $row here
}
Just as an aside, try to get used to using variable names that are as meaningful as possible and use new variables as much as you can. Trying to use short, generic variable names like $a will always lead to confusion since you won't know what it represents unless you find where you declared it every time. Trying to re-use a variable (like you did with $result) can make your life much more difficult since now even if you find an assignment to the variable, it is assigned many different times and (the way you used it) represents completely different types each time. Doing this one thing makes it just a little easier to get the hang of programming since at the very least you'll be able to read and make sense of your own intent when reading your own code.
Please try this code for display multiple marker on map
<script type="text/javascript">
var LocationData = <?php echo json_encode($result); ?>;
function initialize()
{
var myOptions = {zoom:12,mapTypeId: google.maps.MapTypeId.ROAD};
var map =
new google.maps.Map(document.getElementById('map-canvas'), myOptions);
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (var i in LocationData)
{
var p = LocationData[i];
var latlng = new google.maps.LatLng(p[0], p[1]);
bounds.extend(latlng);
var icon = { url: '<?php echo base_url();?>assets/frontend/assets/images/location_pin1.png', // url
scaledSize: new google.maps.Size(40, 70), // scaled size
origin: new google.maps.Point(0,0), // origin
anchor: new google.maps.Point(0, 0) // anchor
};
var marker = new google.maps.Marker({
position: latlng,
map: map,
draggable: true, // enables drag & drop
animation: google.maps.Animation.DROP
icon: icon
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
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", "xxxxx", "yyyy", "zzzzz");
if ($con1->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
}
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 mapOptions = {
zoom: 14
};
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.'
});
The easiest way to get those variables in Javascript is to output them from PHP to JS, there is no direct bridge, so you will need in the HTML output a script block with the values you got from your SQL query, it will be something like this:
<script>
var lat = <?php echo $lat ?>;
var long = <?php echo $long ?>;
</script>
Now you can use this variables in your javascripts to invoke the map, as a note you can add the variables definition to your main JS block as well.
EDIT:
Rename index.html to index.php
<?php include_once('location.php') ?>
<!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(<?php echo $lat ?>,<?php echo $long ?>);
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.'
});
I need some help as I'm trying to call back a JavaScript function with PHP. I created 2 classes which work together perfectly. In the first one exploiting a Google API, I extract the latitude and longitude of a city chosen by a user on my form, and then I pass these values to the second class which exploits another API to show a weather forecast service for that city.
I'd like to add a Google map too, to create this way a more complete service showing a dynamic map with the chosen city.
I noticed with Firebug that the browser is not able to parse correctly the two mentioned properties of the object $map, as you can easily see by yourself.
I really don't know how to call back the js function inside the tag , I need for my purpose.
The simple echo I'm using here with PHP doesn't work here.
Hope someone can help me.
Here's my page
and here's the piece of my code that is not working:
/**
* Check for the real existence of the city, using the
* property $status of the instanced GeoLocalization class, here the object $map.
* This class exploits a Google API.
*/
if ( isset($missing) && empty($missing) && strlen($citta) > 1 && $map->status == 'OK' )
{
/**
* Use some properties of the object $map to show my user
* the chosen city and state in Italian.
* Show even the latitude and the longitudine.
* These values are those passed to the GeoWeather class.
*/
// show the location
echo '<ul id="display_location">' .
'<li class="rosso centra sottolineato grassetto">' . $map->formatted_address . '</li>' .
'<li>' . 'Latitudine: ' . $map->latitude . '</li>' .
'<li>' . 'Longitudine: ' . $map->longitude . '</li>' .
</ul>';
echo '<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>';
echo '<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(<?php echo $map->latitude . ", " . $map->longitude; ?>)
};
map = new google.maps.Map(document.getElementById("googleStaticMap"), mapOptions);
}
</script>';
echo '<script type="text/javascript">initialize();</script>';
echo '<div id="googleStaticMap"></div>';
}
</body>
You can't start a new PHP-block inside a PHP-block.
This:
echo '<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(<?php echo $map->latitude . ", " . $map->longitude; ?>)
};
map = new google.maps.Map(document.getElementById("googleStaticMap"), mapOptions);
}
</script>';
should be:
echo '<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng('. $map->latitude . ','
. $map->longitude .')
};
map = new google.maps.Map(document.getElementById("googleStaticMap"),
mapOptions);
}
</script>';
Other issues:
you must switch the order of these 2 lines(otherwise #googleStaticMap is unknown when you call the function):
echo '<script type="text/javascript">initialize();</script>';
echo '<div id="googleStaticMap"></div>';
Additionaly:
#googleStaticMap currently doesn't have a height. You've set a height of 100%, but as long as the parent element of #googleStaticMap doesn't have a height set via CSS this will not have any effect.
working on some perl code in a .cgi file that loops through a hash list of IP addresses, then runs each IP address through a web service that returns that latitude and longitude of the IP address, then it needs to display each IP address as a marker on a google map. As of right now I have it running through the hashlist and printing the coordinates of each IP address. What I can't figure out is how to display more than one map marker on the google map. I am currently just testing it by hardcoding values to the $latitude and $longitude variables. I am thinking that there needs to be some sort of loop in the javascript that will run through and assignin each coordinate, but I have no idea on how to approach that.
Update: I have added the code from the first answer and have the list successfully printing outside of the loop. The problem I am having now is that the google map will no longer load. I have narrowed the problem down to the javascript where the latitudes and longitudes variable assigned its value.
unless ($result->fault) {
# Print out the results one by one
my $latitude = "LATITUDE = " . $result->valueof('//LATITUDE') . "\n";
my $longitude = "LONGITUDE = " . $result->valueof('//LONGITUDE') . "\n";
#print "MESSAGE = " . $result->valueof('//MESSAGE') . "\n";
$lats .= $latitude . ',';
$lons .= $longitude . ',';
} else {
print "IP2Location Web Service Failed!\n";
print join ', ',
$result->faultcode,
$result->faultstring,
$result->faultdetail;
}
}
chop $lats;
chop $lons;
#printing here to test if the variable is making it out of the loop
print $lats ;
print $lons ;
print <<ENDHTML;
<html>
<head>
<title>IP Lookup Map</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no">
<meta charset="UTF-8">
<style type="text/css">
html, body, #map_canvas {
margin: 0;
padding: 0;
height: 90%;
width: 90%;
}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//If I comment out the following variables the map will load, not sure what the problem is
var latitudes = "$lats".split(",");
var longitudes = "$lons".split(",");
var map;
function initialize() {
var myOptions = {
zoom: 7,
center: new google.maps.LatLng(44, -90),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Creating a marker and positioning it on the map
for(var i = 0; i < latitudes.length; i++){
var latitude = latitudes[i];
var longitude = longitudes[i];
// Creating a marker and positioning it on the map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude,longitude),
map: map
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Obviously you need to save all the latitudes and longitudes, rather than just print them. I'd use 2 globals, outside your unless($result){
my $lats = '';
my $lons = '';
....
$lats .= $latitude . ',';
$lons .= $longitude . ',';
(You might need a chop($lats); chop($lons) after the loop to remove the last comma) Then in your javascript section:
// create two arrays from that lats and lons string using split()
var latitudes = "$lats".split(',');
var longitudes = "$lons".split(',');
.....
// create map code
....
for(var i = 0; i < latitudes.lenght; i++){
var latitude = latitudes[i];
var longitude = longitudes[i];
// Creating a marker and positioning it on the map
var marker = new google.maps.Marker({
position: new google.maps.LatLng(latitude,longitude),
map: map
});
}
Fixed it and have everything working now. The problem was that the $latitude and $longitude variables where still being assigned a bunch of extra text that was not needed. Now it is just assigned the value.
my $latitude = $result->valueof('//LATITUDE');
my $longitude = $result->valueof('//LONGITUDE');