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.'
});
Related
I googled a lot but all the solutions i found didn't work for me (even google maps tutorial). I have a MySQL database where I store latitude and longitude values in Float type columns. I wrote php script which connects to the database and selects those values. The idea is that php script passes an array of longitude and latitude values to JavaScript and then Javascript iterate on that array making new markers on Google Maps. Here is my actual code:
<html>
<head>
<style>
#map {
width: 100%;
height: 700px;
background-color: grey;
}
</style>
</head>
<body>
<?php
$query ="SELECT latitude,longitude FROM markers";
$result_array=Array();
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$latitude=$row['latitude'];
$longitude=$row['longitude'];
$result_array[]=array('latitude'=>$latitude,'longitude'=>$longitude);
}
$json=json_encode($result_array);
$con->close();
?>
<h3>MyMap</h3>
<div id="map"></div>
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 41.5400 , lng: 12.2500},
zoom: 6
});
var array="<?php echo $json_array;?>";
for(var i=0;i<array.length;i++){
var myLatLng=new google.maps.LatLng(lat,lon);
var marker=new google.maps.Marker({
map:map,
position: myLatLng,
});
//}
}
</script>
<script async defer
src=MY GOOGLE API MAP>
</script>
</body>
</html>
Can anyone help me or suggest other ways to do the same thing?
Try putting newlines between <?php and the actual content, like so:
var array=JSON.parse("<?php
echo $json_array;
?>");
The PHP substitution should put the double quotes on the same line.
<html>
<head>
<style>
#map {
width: 100%;
height: 700px;
background-color: grey;
}
</style>
</head>
<body>
<?php
$query ="SELECT latitude,longitude FROM markers";
$result_array=Array();
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$latitude=$row['latitude'];
$longitude=$row['longitude'];
$result_array[]=array('latitude'=>$latitude,'longitude'=>$longitude);
}
$json=json_encode($result_array);
$con->close();
?>
<h3>MyMap</h3>
<div id="map"></div>
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 41.5400 , lng: 12.2500},
zoom: 6
});
var array="<?php echo $json;?>";//here changed
for(var i=0;i<array.length;i++){
var myLatLng=new google.maps.LatLng(lat,lon);
var marker=new google.maps.Marker({
map:map,
position: myLatLng,
});
//}
}
</script>
<script async defer
src=MY GOOGLE API MAP>
</script>
</body>
</html>
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 );
I am having difficulties adding multiple markers to my Google Map. Below is my code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(-35.3075,149.1244)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<?php
$dbc = mysql_connect('localhost', 'username', 'password') or die('Unable to connect to MySQL: '.mysql_error());
mysql_select_db ('database', $dbc) or die('Unable to connect to database: '.mysql_error());
$query = "SELECT * FROM centenary_events WHERE location != ''";
$result = mysql_query($query) or die("Error querying database: ".mysql_error());
while ($row = mysql_fetch_array($result)) {
?>
<script>
var link = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D"<?php echo $row['location']?>"&format=json&diagnostics=true';
$.getJSON(link, function(json) {
console.log("<?php echo $row['title']?>");
console.log("Latitude: " + json.query.results.Result.latitude);
console.log("Longitude: " + json.query.results.Result.longitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(Number(json.query.results.Result.latitude), Number(json.query.results.Result.longitude)),
map: map,
title: 'Hello World!'
});
});
</script>
<?php
}
?>
</head>
<body>
<div id="map-canvas" style="width: 100%; height: 100%"></div>
</body>
</html>
Using PHP and MySQL, I am attempting to loop through a database to gather values, and then use those values to add markers to a map. The map is working, but the marker functionality is not. Please help.
You're not doing it in the way you need to :),
So to add multiple marker or what ever into map from php, the best way would be while proccesing the php fetch those data you wanna display and send them to javascript (json,xml or whatever js can parse) or playing with ajax (which is one level higher the this solution), in your case should be like the follow:
HTML&PHP
<?php
$dbc = mysql_connect('localhost', 'username', 'password') or die('Unable to connect to MySQL: '.mysql_error());
mysql_select_db ('database', $dbc) or die('Unable to connect to database: '.mysql_error());
$query = mysql_query("SELECT * FROM centenary_events WHERE location != ''");
$myData = array();
while($row = mysql_fetch_array($result)){
$myData = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
//here is the magic :)
var myData = <?php echo json_encode($myData) ?>;
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(-35.3075,149.1244)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//and you must set this code here because the map is just initialed
$.each(myData, function(){
var link = 'generate your link here with myData array';
$.getJSON(link, function(json) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(Number(json.query.results.Result.latitude), Number(json.query.results.Result.longitude)),
map: map,
title: 'Hello World!'
});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
...
The code may have errors, I just wanted to create you an idea how it should look
Im trying to pull values from mysql database and use to draw a marker on the map but it doesnt seem to work, I've tested the database connection and its working fine but i dont know what the problem is
<html>
<?PHP
include("config.php");
$sql="SELECT * FROM lat long";
$rs = mysqli_query($con,$sql) or die(mysql_error());
$array=mysqli_fetch_array($rs);
$Lat=$array['lat'];
$Lng=$array['long'];
?>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
#select_route {width:20%;height:200px;}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map = "";
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(30, 31),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function addMarker() {
var LatLong= new google.maps.LatLng(<?php echo lat ?> ,<?php echo lng ?>);
//Problem Lies here in passing the lat and long i suppose
marker = new google.maps.Marker({
position:LatLong,
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: "<p style='color:blue'>UserInfo</p>" + '<button type="button">Navigate</button>' + '<IMG BORDER="0" ALIGN="Left" SRC="testpic.png">' ,
position: new google.maps.LatLng(30, 31),
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
};
</script>
<div id ="welcome" style="color:#0000FF">
<h3>Welcome to GoogleMaps </h3>
</div>
</head>
<body onload="initialize();addMarker();">
<div id="map_canvas" style="width:60%; height:80%"></div>
First thing that I saw is that you are missing the $ sign before the php variables in the following line:
var LatLong= new google.maps.LatLng(<?php echo lat ?> ,<?php echo lng ?>);
Also the variable names are not correct. You defined the variables as $Lng and $Lat starting with capital letters but in the above code you are using lowercase.
So change that line to:
var LatLong= new google.maps.LatLng(<?php echo $Lat ?> ,<?php echo $Lng ?>);
Besides this, you might have to adjust your query. It would make more sense if it was something along these lines:
"SELECT * FROM table_name" where table_name is the name of your table.
Finally, if it still does not work please post the javascript errors form your browser's console and the php error log to make it easier for me to see the errors.
I did what you advised, map is displayed correctly, but have no markers. Maybe I've made some mistakes?
Code:
`
mysql_connect("xxx", "xxx", "xxx") or die("Error connecting to database: ".mysql_error());
mysql_select_db("xxx") or die(mysql_error());
$querz = "SELECT * FROM markers";
$result = mysql_query($querz)
or die("Query failed");
while ($row = mysql_fetch_array($result)) {
$lat = "$row[lat]";
$lng = "$row[lng]";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="iso-8859-2">
<title>Simple icons</title>
<style>
html, body, #map-canvas {
height: 600px;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(52, 19)
}
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var image = '20_blue.png';
var myLatLng = new google.maps.LatLng(<?php print($lat); ?>,<?php print($lng); ?>);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map-canvas"></div>
</body>
/html>`
my question: is there any way to display markers from Mysql database instead of use specific lat and lng , like I did in the code above ? How ? I tried google tutorials but it had some bugs (I' ve already asked another question about it).
You need a server side language to connect to your database (in your case I advise you to use PHP which is the simplest). You will be able to select your datas from the database with PDO.
Edit:
You need to write your php loop inside your javascript code. Here you are adding only one marker to your map, the last one you selected with your query. Also make sure the table is not empty.
You can do something like that:
<script type="text/javascript">
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(52, 19)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var image = '20_blue.png';
<?php while($row = mysql_fetch_array($result)): ?>
var myLatLng = new google.maps.LatLng(<?php echo $row['lat']; ?>, <?php echo $row['lon']; ?>);
var beachMarker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: image
});
<?php endwhile; ?>
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
call lat and long from DB and assing them to
$lat
$long
and then you can call them like
var myLatLng = new google.maps.LatLng(<?php print($lat); ?>,<?php print($long); ?>);
This is just an idea, you can turn it as per your needs.