Coding a delivery service Web App using Google Map API. Haven't had a problem until I started to use multi-dem array as LatLng Reference. Now I'm getting this weird error --
"InvalidValueError: not a LatLng or LatLngLiteral"
I used a similar array reference for LatLng earlier and no problem, but now that it's multi-dem array I got this weird error.
<?php
session_start();
require 'ConnectTest.php';
// IF YOU'RE NOT LOGGED IN, KICK BACK TO LOGIN SCREEN
if(!isset($_SESSION['username']) || !isset($_SESSION['password'])){
header("Location:signin.php");
}
$servername = "localhost:3306";
$user = "sonic_client";
$pass = "client";
$dbName = "sonicStrains";
$drop = "DROP TABLE ".$_SESSION['username']."_deliveries";
mysqli_query($server, $drop);
//CREATE INDIVIDUAL DRIVER TABLE TO HOLD DELIVERIES
$createQuery = "CREATE TABLE ".$_SESSION['username']."_deliveries (
transaction_id VARCHAR(13),
timePaid INT(11),
username VARCHAR(30),
user_location VARCHAR(255),
user_lat float(10,6),
user_long float(10,6),
item_name VARCHAR(20),
item_quantity float,
driver_username VARCHAR(60),
driver_lat float(10,6),
driver_long float(10,6),
on_delivery tinyint(1))";
$created = mysqli_query($server, $createQuery);
if ($created){
//query the deliveries for open deliveries up untill 5 deliveries
$queryString = "SELECT * FROM deliveries LIMIT 5";
$query = mysqli_query($server, $queryString);
if($query){
// CREATE ARRAY TO HOLD QUERY ROWS
$rows = array();
while($queryresult = mysqli_fetch_assoc($query)){
$rows[] = $queryresult;
}
echo floatval($rows[0]['user_lat']);
echo"<br>";
//INSERT & UPDATE THE TABLES WITH DELIVERY QUERIES
foreach($rows as $row){
// INSERT INTO INDIVIDUAL DRIVER TABLE
$insertQuery = "INSERT INTO ".$_SESSION['username']."_deliveries (transaction_id, user_location, user_lat, user_long) VALUES('$row[transaction_id]', '$row[user_location]', '$row[user_lat]', '$row[user_long]')";
$insertExec = mysqli_query($server, $insertQuery);
// UPDATE MASTER LIST OF DELIVERIES SO THAT OTHER DRIVERS DONT QUERY SAME ORDER
$updateQuery = "UPDATE deliveries SET on_delivery=true, driver_username='$_SESSION[username]' WHERE transaction_id='$row[transaction_id]'";
$updateExec = mysqli_query($server, $updateQuery);
}
}else{echo mysqli_error($server);}
}else{echo mysqli_error($server);}
if(isset($_GET['pop'])){
array_shift($rows);
echo print_r($rows);
}
echo<<<_
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div class="Banner">
<div class="TitleText">Sonic Strains ©</div>
</div>
<div class="login">Logout</div>
<div class="gallery" id="container">
<div class="map" id="mapInsert"></div>
<div class="navButton">Start Nav</div><div class="orderButton">Order Details</div>
<div class="abortButton">Abort</div><div class="confirmButton" onclick="shiftOrder()">Confirm</div><div class="disclaimer"></div>
</div>
<script>
function initMap() {
navigator.geolocation.getCurrentPosition(function(position) {
var initialLocation = {lat:$rows[0]['user_lat'], lng:$rows[0]['user_long']};
var Map = new google.maps.Map(document.getElementById('mapInsert'));
Map.setCenter(initialLocation);
Map.setZoom(13);
// MAKE ANOTHER MARKER FOR THE CLIENT LOCATION
var userLocation = {lat:$rows[0]['user_lat'], lng:$rows[0]['user_long']};
var marker = new google.maps.Marker({
position:userLocation,
map:Map,
draggable:false,
clickable:false
});
marker.setMap(Map);
}, function(positionError) {
alert('Location could not be found');
},{enableHighAccuracy:true, timeout: 3000, maximumAge:1000});
}
function shiftOrder(){
var http = new XMLHttpRequest();
http.onreadystatechange = function(){
console.log(this.responseText);
}
http.open("GET", "driverIndex.php?pop='pop'", true);
http.send();
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[API_KEY]&callback=initMap"
async defer></script>
</body>
</html>
_;
?>
Here's a peek at one element of the ref array --
array(5) { [0]=> array(12) { ["transaction_id"]=> string(13) "5c2fb27078926" ["timePaid"]=> string(1) "0" ["username"]=> string(0) "" ["user_location"]=> string(44) "1301 Bataan St NW, Washington, DC 20036, USA" ["user_lat"]=> string(9) "38.907246" ["user_long"]=> string(10) "-77.037292" ["item_name"]=> string(18) "girl_scout_cookies" ["item_quantity"]=> string(1) "1" ["driver_username"]=> string(7) "Driver1" ["driver_lat"]=> string(8) "0.000000" ["driver_long"]=> string(8) "0.000000" ["on_delivery"]=> string(1) "1" }
Again, I've tried to parse the lat & long with floatval() because it says it's not a number
var initialLocation = {lat:floatval($rows[0]['user_lat']), lng:floatval($rows[0]['user_long'])};
but i get -- "floatval not defined"
The PHP variables aren't inside brackets --
var initialLocation = {lat:{$rows[0]['user_lat']}, lng:{$rows[0]['user_long']}};
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 a database with 6 Nations rugby results and teams, and I want to get the data from the results database using AJAX and display on a php page. This is a page i'm using called getData.php
<?php
$year=$_GET['year'];
$connection = mysqli_connect("localhost","root","");
mysqli_select_db($connection,"6nationsDB");
// for results
$result = mysqli_query($connection,"SELECT * FROM results WHERE
year(`date`)='$year' ORDER BY rnd, date");
$rs = array();
$i=0;
while($rs[] = mysqli_fetch_assoc($result)) {
// do nothing ;-)
}
// for team details
$result2 = mysqli_query($connection,"SELECT * FROM teams ORDER BY id");
$rs2 = array();
$i=0;
while($rs2[] = mysqli_fetch_assoc($result2))
{
}
mysqli_close($connection);
unset($rs[count($rs)-1]); //removes a null value
// print("{ \"results\":" . json_encode($rs) . "}");
print("{ \"results\":" . json_encode($rs) . " , \"teams\":" .
json_encode($rs2) . "}");
?>
Trying to access the select statements in getData.php to get data from the database
Browse.php
<link rel="stylesheet" href="design.css" type="text/css">
<!DOCTYPE html>
<html>
<div id="getData"></div>
<script type ="text/javascript">
dis();
function dis()
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "getData.php",false);
xmlhttp.send(null);
document.getElementById("getData").innerHTML=xmlhttp.responseText;
}
</script>
Okay. So i've been here all day, reading and following all the solutions about this topic but i got nothing. Nothing works. Can you show me how to do it, with complete and understandable example. Im new to JavaScript and PHP, so how can i get array values from a PHP file to JavaScript. I tried doing this: var locations = <?php echo json_encode($location); ?>; but i gives me error. and no one answered why. This code here:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var locations = [
['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
['Camarillo Household', 6.4345278, 125.58975, 2],
['Perez Household', 6.4343889, 125.59202777777777, 3],
['Usman Household', 6.4338056, 125.59191666666666, 4],
['Lim Household', 6.4333889, 125.59419444444444, 5]
];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(6.40, 125.60),
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>
</body>
</html>
i want to change the value of variable locations from the value from my database. so i got this PHP file:
<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
// output data of each row
for($i=0;$i<mysqli_num_rows ( $result );$i++){
$row=mysqli_fetch_row($result);
$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));
//echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
}
}else{echo "0 results";}
?>
it works fine. it outputs the data from the database. now what i want to know is how can i convert that value from the database to a value i can use in place of the locations variable so that the markers will appear on the map? var locations = <?php echo json_encode($location); ?>; this guy give me error, i followed every instruction i can, but still it's error. can u modify my code so that it works or can u just point me out in the WORKING/FUNCTIONAL code there is to your knowledge. Please, help me. I'm in deep trouble here.
Try to change location[] variable from :
$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));
to
$location[]= array($row[0],$row[1],$row[2],($i+1));
I have added full code below and its working :
<?php
$servername = "host";
$username = "username";
$password = "password";
$dbname = "dbname";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql='SELECT a.Household_Name, b.Latitude, b.Longitude FROM household a, location b WHERE a.Household_ID = b.Household_ID;';
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
// output data of each row
for($i=0;$i<mysqli_num_rows ( $result );$i++){
$row=mysqli_fetch_row($result);
$location[]= array($row[0],$row[1],$row[2],($i+1));
//echo "Household Name: " . $row[0]. " - Latitude: " . $row[1]. " - Longitude " . $row[2]. " " .($i+1)."<br>";
}
}else{echo "0 results";
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<title>Google Maps Multiple Markers</title>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
</head>
<body>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
/*var locations = [
['Municipal Hall', 6.414333734068895, 125.61093270778656, 1],
['Camarillo Household', 6.4345278, 125.58975, 2],
['Perez Household', 6.4343889, 125.59202777777777, 3],
['Usman Household', 6.4338056, 125.59191666666666, 4],
['Lim Household', 6.4333889, 125.59419444444444, 5]
];*/
var locations = <?php echo json_encode($location); ?>;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(6.40, 125.60),
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>
</body>
</html>
Your array is not "realy" an array
if your code is :
$location[]= array($row[0].', '.$row[1].', '.$row[2].','.($i+1));
I think the result will be somthing like this :
<script type="text/javascript">
var locations = [["Municipal Hall, 6.414333734068895, 25.61093270778656, 1"],["Camarillo Household', 6.4345278, 125.58975, 2"],......];
.....
</script>
try with :
$location[]= array($row[0],$row[1],$row[2],($i+1));
Edit:
I don't recommend to use this mean to pass PHP array to JS beacause it overload the html page and navigator can't cahe the content of your array. the beter way to do this is to use Ajax function at the page loading with this http://api.jquery.com/jquery.ajax/
i have two files one index.php and another phpsqlajax_genxml3.php
Here in file 1 i am getting value through browser url and storing that value in $driver_id variable.
Now i want to get that value in file 2 when my file 1 control goes to file 2. and using that $driver_id value i want to fire a query.
I have copy paste my both files code below, pleasae take a look and please help me if u can solve my problem.
file 1 : index.php
<?php
if(isset($_GET["driver_id"])){
echo $driver_id = trim($_GET["driver_id"]);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<link rel="stylesheet" href="dist/css/skins/skin-blue.min.css">
<link rel="stylesheet" type="text/css" href="css/admin-style.css">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var map, infoWindow, intervalId;
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(18.489023, 73.814462),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
infoWindow = new google.maps.InfoWindow;
// Trigger downloadUrl at an interval
intervalId = setInterval(triggerDownload, 500);
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function triggerDownload() {
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml3.php", function(data, $driver_id) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("driver");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("mobile_number");
/*var type = markers[i].getAttribute("type");*/
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lattitude")),
parseFloat(markers[i].getAttribute("longitude")));
var html = "<b>" + name + "</b> <br/>" + address + "</b> <br/>" + point;
var icon = new google.maps.MarkerImage("http://labs.google.com/ridefinder/images/mm_20_red.png");
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
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 class="hold-transition skin-blue sidebar-mini" onload="load()">
<div class="wrapper">
<div class="content-wrapper">
<section class="content">
<div class="row">
<div class="col-md-12" id="map" style="height: 500px"></div>
</div>
</section>
</div>
</div>
<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="dist/js/app.min.js"></script>
</body>
</html>
file 2 : file 2 is fetching data as xml from database and returning it to index.php
<?php
error_reporting(E_ERROR | E_PARSE | E_WARNING);
// Start XML file, create parent node
/*if(isset($_GET['driver_id'])) {
$driver_id = $_GET['driver_id'];
}*/
$dom = new DOMDocument("1.0");
$node = $dom->createElement("driver");
$parnode = $dom->appendChild($node);
$connection=mysql_connect ('localhost', 'root', '');
if (!$connection) { die('Not connected : ' . mysql_error());}
$db_selected = mysql_select_db('trackusdown', $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$query = "SELECT * FROM driver WHERE driver_id='1'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("driver");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['driver_name']);
$newnode->setAttribute("mobile_number", $row['driver_mobile_number']);
$newnode->setAttribute("lattitude", $row['driver_lattitude']);
$newnode->setAttribute("longitude", $row['driver_longitude']);
/*$newnode->setAttribute("driver_id", $driver_id);*/
}
echo $dom->saveXML();
?>
It wasn't terribly clear, from the question, exactly what the problem was but I think you were having trouble sending the driver_id via ajax to the php script which then queried the database to produce an xml file?
The ajax function and callback looked unusual and have been modified slightly here. I hope this is more or less what you meant to achieve ( though it is not tested )
phpsqlajax_genxml3.php
----------------------
<?php
error_reporting( E_ERROR | E_PARSE | E_WARNING );
/* Is `driver_id` a string or an integer? */
$driver_id = isset( $_GET['driver_id'] ) && !empty( $_GET['driver_id'] ) ? filter_input( INPUT_GET, 'driver_id', FILTER_SANITIZE_STRING ) : false;
if( $driver_id ){
$connection=mysql_connect ('localhost', 'root', '');
if( !$connection ) die( 'Not connected : ' . mysql_error() );
$db_selected = mysql_select_db('trackusdown', $connection);
if ( !$db_selected ) die ( 'Can\'t use db : ' . mysql_error() );
/*
As you are still using the deprecated mysql_* extensions you
need to be ultra careful with the data supplied so should filter
it as much as needed
*/
$driver_id=mysql_real_escape_string( strip_tags( $driver_id ) );
$query = "SELECT * FROM driver WHERE driver_id='{$driver_id}';";
$result = mysql_query( $query );
if ( $result ) {
$dom = new DOMDocument("1.0");
$node = $dom->createElement("driver");
$parnode = $dom->appendChild( $node );
while( $row = #mysql_fetch_assoc($result) ){
$node = $dom->createElement("driver");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name",$row['driver_name']);
$newnode->setAttribute("mobile_number", $row['driver_mobile_number']);
$newnode->setAttribute("lattitude", $row['driver_lattitude']);
$newnode->setAttribute("longitude", $row['driver_longitude']);
}
header("Content-type: text/xml");
echo $dom->saveXML();
mysql_free_result( $result );
mysql_close( $connection );
$dom=$node=$result=$connection=null;
exit();
}
}
?>
html page
---------
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
<link rel="stylesheet" href="https://code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css">
<link rel="stylesheet" href="dist/css/AdminLTE.min.css">
<link rel="stylesheet" href="dist/css/skins/skin-blue.min.css">
<link rel="stylesheet" type="text/css" href="css/admin-style.css">
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script type="text/javascript">
var map, infoWindow, intervalId;
<?php
/*
could use pure javascript for this instead but this is easy.
The driver_id needs to be sent via ajax so make it globally available
to make things easier with your functions.
*/
echo "var driver_id='".trim( $_GET["driver_id"] )."';";
?>
function load() {
map = new google.maps.Map( document.getElementById("map"), {
center: new google.maps.LatLng(18.489023, 73.814462),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
infoWindow = new google.maps.InfoWindow;
// Trigger downloadUrl at an interval
intervalId = setInterval(triggerDownload, 500);/* Every half second? */
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function triggerDownload() {/* The url has the driver_id parameter set */
downloadUrl.call( this, 'phpsqlajax_genxml3.php?driver_id='+driver_id, cbdownloadUrl );
}
function cbdownloadUrl( response ){/* callback function: do something with the returned XML */
var markers = response.documentElement.getElementsByTagName("driver");
for ( var i = 0; i < markers.length; i++ ) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("mobile_number");
var point = new google.maps.LatLng(
parseFloat( markers[i].getAttribute("lattitude") ),
parseFloat( markers[i].getAttribute("longitude") )
);
var html = "<b>" + name + "</b> <br/>" + address + "</b> <br/>" + point;
var icon = new google.maps.MarkerImage( "http://labs.google.com/ridefinder/images/mm_20_red.png" );
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow( marker, map, infoWindow, html );
}
}
function downloadUrl( url, callback ) {/* Ajax request to fetch xml */
var request = window.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function () {
if( request.readyState==4 && request.status == 200 ) {
callback( request.responseXML );
}
};
request.open('GET', url, true);
request.send( null );
}
</script>
</head>
<body class="hold-transition skin-blue sidebar-mini" onload="load()">
<div class="wrapper">
<div class="content-wrapper">
<section class="content">
<div class="row">
<div class="col-md-12" id="map" style="height: 500px"></div>
</div>
</section>
</div>
</div>
<script src="plugins/jQuery/jQuery-2.1.4.min.js"></script>
<script src="bootstrap/js/bootstrap.min.js"></script>
<script src="dist/js/app.min.js"></script>
</body>
</html>
use SESSION to set value on index.php as
if(isset($_GET["driver_id"])){
session_start();
$_SESSION['driver_id']=trim($_GET["driver_id"]);
$_SESSION['order_id']=trim($_GET["order_id"]);
and get that values on phpsqlajax_genxml3.php using SESSION as
$driver_id = $_SESSION['driver_id'];
I'm not that experienced in Javascript and I'm kind of stuck with ammap (http://www.amcharts.com/javascript-maps/).
The idea is to add some locations to the map from a mysql database. Their tutorial chapter on this is outdated and recommends using the DataLoader plugin instead (http://www.amcharts.com/tutorials/using-data-loader-plugin/). This, however, is for amcharts rather than ammap, and I can't figure it out.
Here's the code:
index.php
<script src="ammap/ammap.js" type="text/javascript"></script>
<link rel="stylesheet" href="ammap/ammap.css" type="text/css"
media="all" />
<script src="ammap/maps/js/germanyLow.js" type="text/javascript"></script>
<script
src="http://www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"
type="text/javascript"></script>
<script type="text/javascript">
AmCharts.makeChart( "mapdiv", {
"type": "map",
"dataProvider": {
"map": "germanyLow"
}
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true
},
} );
</script>
<div id="mapdiv" style="width: 600px; height: 400px;"></div>
data.php
<?php
$server = "localhost";
$user = "root";
$pass = "";
$db = "map";
$conn = new mysqli ( $server, $user, $pass, $db);
if ($conn->connect_error) {
die ( "Connection failed: " . $conn->connect_error );
}
$sql = "SELECT latitude, longitude FROM map";
$result = $conn->query($sql);
if($result->num_rows > 0){
$data = array();
while($row = $result->fetch_assoc()){
$data[] = $row;
}
}else{
//
}
$string = json_encode($data);
echo $string;
?>
The json string of the data.php file is:
[{"latitude":"48.47","longitude":"9.11"},{"latitude":"53.33","longitude":"10"}]
The map won't load with this code. If I comment out the dataLoader part, the map itself loads just fine. Does anybody know how to use the dataLoader properly? Any help would be greatly appreciated.
Solved with help from amcharts support crew. For those of you interested in the solution:
AmCharts.makeChart("mapdiv", {
"type": "map",
"data": {
"map": "germanyLow"
},
"dataLoader": {
"url": "data.php",
"format": "json",
"showErrors": true,
"postProcess": function(data, config, map) {
// create a new dataProvider
var mapData = map.data;
// init images array
if (mapData.images === undefined)
mapData.images = [];
// create images out of loaded data
for(var i = 0; i < data.length; i++) {
var image = data[i];
image.type = "circle";
mapData.images.push(image);
}
return mapData;
}
}
});