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
Related
I have made a database in MySQL with some information and long/lat data in it. I would like this data to appear on my google maps page as markers, so that I do not have to manually add markers to a script.
I have followed several tutorials and have tried several scripts, with the one shown below being the only one that didn't come up with errors for me. However, the markers do not appear on the map. I have mainly followed instructions from this link: https://developers.google.com/maps/documentation/javascript/mysql-to-maps
My data does appear on the xml file as it states in the tutorial, having a look at my sourcecode for the map I find the following error at line 54 of the index.html script:
Uncaught ReferenceError: customLabel is not defined
I have tried fixing this, but I end up messing up the entire script. My question is, could anyone help me fix this error so that my markers appear on the map created in the index.html file?
I have 3 separate scripts: a "config.php" for my log in details, a "maps_xml.php" to call the data and an "index.html" to make the map and add the data as markers.
Config script:
<?php
$username="mydatabase_username";
$password="12345";
$database="mydatabase";
?>
Maps_XML.php script:
<?php
require("config.php");
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysqli_connect (localhost, $username, $password);
if (!$connection) {
die('Not connected : ' . mysqli_error());
}
// Set the active MySQL database
$db_selected = mysqli_select_db($connection, $database);
if (!$db_selected) {
die ('Can\'t use db : ' . mysqli_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM userlocations WHERE 1";
$result = mysqli_query($connection, $query);
if (!$result) {
die('Invalid query: ' . mysqli_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo "<?xml version='1.0' ?>";
echo '<markers>';
$ind=0;
// Iterate through the rows, printing XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// Add to XML document node
echo '<marker ';
echo 'id="' . $row['id'] . '" ';
echo 'name="' . parseToXML($row['name']) . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo '/>';
$ind = $ind + 1;
}
// End XML file
echo '</markers>';
?>
*
Index.html script:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>User 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: 100%;
margin: 0;
padding: 0;
}
</style>
</head>
<html>
<body>
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(51.153844, 5.942341),
zoom: 12
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('maps_xml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var id = markerElem.getAttribute('id');
var name = markerElem.getAttribute('name');
var address = markerElem.getAttribute('address');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = address
infowincontent.appendChild(text);
var icon = customLabel[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
label: icon.label
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_APIKEY &callback=initMap">
</script>
</body>
</html>
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
I have a problem with google maps markers. I want to use polish characters in the names of the markers. As i have in my db. This is the file which i use to create proper (afaik) XML.
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
// Opens a connection to a MySQL server
$connection=mysql_connect ('localhost', $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Start XML file, echo parent node
echo '<markers>';
// Iterate through the rows, printing XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
echo '<marker ';
$test = $row['name'];
//$test2 = string utf8_encode ( string $test );
echo 'name="' . $test . '" ';
echo 'address="' . parseToXML($row['address']) . '" ';
echo 'lat="' . $row['lat'] . '" ';
echo 'lng="' . $row['lng'] . '" ';
echo 'city="' . $row['city'] . '" ';
echo '/>';
}
// End XML file
echo '</markers>';
I get proper output from my db using this file (browser display polish characters properly) but when i create a map using:
<!DOCTYPE html >
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBdj-LlQrTCj6bQcAq4fxONy9MaZcXvfc8"
type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(50.046465, 19.913828),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("markergen.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("city");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map"></div>
</body>
</html>
Then i get whole data, but without correctly displayed polish characters.
I know that i should probably use
string utf8_encode ( string $data )
but i did try to put it in first file to convert data and fail.
So my question is where i should put it exactly into my code? Or is there any other/better option to do this.
EDIT:
I'm now trying to use DOM objects like this:
<?php
require("../test1/phpsqlinfo_dbinfo.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$mysqli = new mysqli("localhost", $username, $password, $database);
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (!$mysqli->set_charset("utf8")) {
printf("Error loading character set utf8: %s\n", $mysqli->error);
exit();
} else {
printf("Current character set: %s\n", $mysqli->character_set_name());
}
// Select all the rows in the markers table
$query = "SELECT * FROM markers WHERE 1";
$result = $mysqli->query($query);
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysqli_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['name']);
$newnode->setAttribute("address", $row['address']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("city", $row['city']);
}
echo $dom->saveXML();
?>
But now i have marker inside of marker in results like: <marker><marker>...</marker></marker> with data ofc. How to fix it? Still i'm not sure that data are correctly encoded but should be.
No, you should not use utf8_encode().
You should however use ext/mysqli or ext/pdo (not the old, depreacted and removed ext/mysql). Set the connection encoding to UTF-8 to get all strings as UTF-8 from the database.
Then use an XML library (DOM or XMLWriter) to generate the XML output. The libraries will encode/escape special characters as needed.
It will provide the missing XML declaration, too.
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 new to Javascript. I want to fetch lat-long from MySQL (more then 100) and use it to add markers on Google Maps.
To do this I think i've to use php -server side programming. I am able to pass array from PHP to Javascript. Here it is
<?
mysql_connect('localhost', 'username', 'pwd') or die(mysql_error());
echo "Connected to MySQL<br />";
mysql_select_db("pro_user") or die(mysql_error());
$result = mysql_query("SELECT * FROM info");
$no=count($result);
$i=0;
while($row = mysql_fetch_array( $result ))
{
$a[$i]=$row['city'];
$b[$i]=$row['loc_lat'];
$c[$i]=$row['loc_long'];
$i++;
}
?>
<html>
<head>
<script type="text/javascript">
function initialize()
{
var latlng = new google.maps.LatLng(22.3038945, 70.8021599);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
<? for($i=0;$i<count($a); $i++)
{
echo "a[$i]='".$a[$i]."';\n";
echo "b[$i]='".$b[$i]."';\n";
echo "c[$i]='".$c[$i]."';\n";
}
?>
function createMarker(latitude,longitude,title)
{
var markerLatLng = new google.maps.LatLng(latitude,longitude);
var marker = new google.maps.Marker({ position: markerLatLng, map: map, title: title });
}
createMarker(22.3038945, 70.8021599,'Gujarat');
for(i=0;i<a.length;i++)
{
document.write(a[i]);
document.write(b[i]);
document.write(c[i]);
initialize().createMarker(b[i], c[i], a[i]);
}
}
</script>
</head>
<body onload="getData()"></body>
</html>
Now I am stuck. I am not able to pass Javascript array to make markers.
There is a very simple tutorial on the google maps website for doing this using PHP / XML / MySQL and Javascript ....
http://code.google.com/apis/maps/articles/phpsqlajax.html