In 2 weeks I explored much about Google maps. I am try read a forum and tutorial. But I got this problem when I am going to develop a GIS web. I am using Google maps apiv3, postgre database, and php. I have so much row in my database. Now I only can show multiple marker based on my database, but what I after is the marker have a unique icon based on column content in database like a type 1 = 1.png type 2 = 2.png. the problem is the type is too many, so it is impossible to definition them by manual (because so many type, I already have about 30 type of content in database column ) . I get database value using json. I've already try read forum and some tutorial, but I can't find the answer. sorry for my bad english. please help me, thanks.
this is the code index.php and json.php :
<html lang="en">
<head>
<script type="text/javascript">
function initialize(){
var peta;
var gambar_tanda;
gambar_tanda = 'assets/images/enseval.jpg';
var x = new Array();
var y = new Array();
var customer_name = new Array();
var rayon_name = new Array();
// posisi default peta saat diload
var lokasibaru = new google.maps.LatLng( -1.2653859,116.83119999999997);
var petaoption = {
zoom: 5,
center: lokasibaru,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
peta = new google.maps.Map(document.getElementById("map_canvas"),petaoption);
var infowindow = new google.maps.InfoWindow({
content: ''
});
// memanggil function ambilpeta() untuk menampilkan koordinat
url = "json.php";
$.ajax({
url: url,
dataType: 'json',
cache: false,
success: function(msg){
for(i=0;i<msg.enseval.customer.length;i++){
x[i] = msg.enseval.customer[i].x;
y[i] = msg.enseval.customer[i].y;
customer_name[i] = msg.enseval.customer[i].nama_customer;
//rayon_name[i] = msg.enseval.customer[i].nama_rayon
var point = new google.maps.LatLng(parseFloat(msg.enseval.customer[i].x),parseFloat(msg.enseval.customer[i].y));
tanda = new google.maps.Marker({
position: point,
map: peta,
icon: gambar_tanda,
clickable: true
});
bindInfoWindow(tanda, peta, infowindow, msg.enseval.customer[i].nama_customer );
}
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
function bindInfoWindow(tanda, peta, infowindow, data) {
google.maps.event.addListener(tanda, 'click', function() {
infowindow.setContent(data);
infowindow.open(peta, tanda);
});
}
</script>
<?php
require ('config.php');
$rayon = $_POST['rayon'];
$cabang = $_POST['org_id'];
//echo "$rayon, $cabang, $rayonhasil";
$sql = "SELECT distinct org_id, customer_name, attribute16, attribute17 FROM hasilgis";
$data = pg_query($sql);
$json = '{"enseval": {';
$json .= '"customer":[ ';
while($x = pg_fetch_array($data)){
$json .= '{';
$json .= '"id_customer":"'.$x['org_id'].'",
"nama_customer":"'.htmlspecialchars($x['customer_name']).'",
"x":"'.$x['attribute17'].'",
"y":"'.$x['attribute16'].'"
},';
}
$json = substr($json,0,strlen($json)-1);
$json .= ']';
$json .= '}}';
echo $json;
?>
I'm not sure what's the problem :)
The only thing you must do is to generate icons for all types. You don't have to do it manually - just create a scipt that will generate icons of different colors for every type and name it like 1.jpg, 2.jpg, ...
Pass type via your json message and than on client side create icon url dynamically:
gambar_tanda = 'assets/images/'+msg.enseval.customer[i].type+'.jpg';
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>
Okay, so I have searched and tried different methods, and still don't know why when I add in the 'name' to my code, it stops working (just shows blank page), but if I remove 'name' it works just fine.
<?php
$sql = "SELECT * FROM users WHERE e_lat != ''";
$result = $link->query($sql);
while($row = $result->fetch_assoc())
{
$idx = $row['IDX'];
$name = $row['name'];
$lat = $row['e_lat'];
$lon = $row['e_long'];
echo ("addMarker($lat, $lon, $idx, $name);\n");
}
?>
function addMarker(lat, lng, idx, name)
{
var html = 'IDX: ' + idx + '<br>Name: ' + name;
var pt = new google.maps.LatLng(lat, lng);
bounds.extend(pt);
var infowindow = new google.maps.InfoWindow({
content: html,
maxWidth: 300
});
var marker = new google.maps.Marker({
id: idx,
position: pt,
icon: icon,
map: map,
content: html
});
google.maps.event.addListener(marker, 'click', function()
{
infowindow.open(map,marker);
});
}
Your $name is a string so it needs to be quoted. Use:
echo ("addMarker($lat, $lon, $idx, '$name');\n");
You also should use the developer console in the future. That will help you debug these issues.
https://developers.google.com/web/tools/chrome-devtools/console/
(or if you are using another browser search for how to access its developer's tools, most browser today have some debugging feature in them)
My objective is to obtain data from a table in a database and show it on the map. My table has three columns: LATITUD (stores the latitude)(type=float(10,6)), LONGITUD (stores the longitude)(type=float 10,6) and ASUNTO(stores the information)(type=VARCHAR). The first two have information of the location of the marker, while the third column stores information related to the marker. The content of this last column is the one I want to show with an info window.
To achieve this inside the body element of the page i have decided to insert a script element (javascript) which I use to create the map and to load all the information related to it.
Inside this javascript code I have included PHP code which is in charge of making a query to the database to obtain the content of the table we mentioned at the beggining in an associative array. Inside this code through a while loop I want to load all the markers with their corresponding info windows.
Loading the markers didn't gave me any problem, to load them I used this while loop code.
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var myLatlng1 = new google.maps.LatLng('.
$row['LATITUD'].', '.$row['LONGITUD'].');
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
});';
}
Inside the PHP script I inserted this code and works fine to me. I have the problem when I want to add info windows for each marker which contain the information stored in the "ASUNTO" column mentioned at the beggining. When I modify the code shown above to add info windows I have problems. The code that is giving me problems is the one below.
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var asunto = '. $row['ASUNTO'] . ';';
echo ' var myLatlng1 = new google.maps.LatLng('.
$row['LATITUD'].', '.$row['LONGITUD'].');
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: asunto
});
infowindow.open(map, marker1);
';
}
I think that the code line that is giving me problems is the first one inside the loop, which I will show now below.
echo ' var asunto = '. $row['ASUNTO'] . ';';
The reason I believe this, is because the "infowindow" variable when I change its content to a string which is not obtained through PHP and is directly inserted doesn't gives me any problem and displays an info window when it is called using the "open"method. The next code below doesn't gives me any problem.
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var myLatlng1 = new google.maps.LatLng('.
$row['LATITUD'].', '.$row['LONGITUD'].');
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
});
var infowindow = new google.maps.InfoWindow({
content: "hello"
});
infowindow.open(map, marker1);
';
}
As you can see the content of the infowindow have changed and when I changed it, it worked correctly and the map was able to load. I would like to show info windows which display the information stored in the database rather than the string "hello" of the example above.
I would like to know why my approach is failing and how to resolve the problem in order to be able to show the info windows I want for each marker.
The problem is not with the database, nor the php. The problem is where you echo that data.
One simple example, it's quite obvious that this won't work
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
echo ' var myLatlng1 = new google.maps.LatLng('.
...
The while-loop creates multiple instances of this code. The variable myLatlng1 will simply be overwritten.
What you need to do, is separate the data from the functions.
So you generate 1 var.
It should be something like this (my php is a bit rusty, I hope I'm not generating errors):
<?php
$data = array(); // we make an empty object/array, we will fill it with the data in the rows
while ($row = $resultado->fetch( PDO::FETCH_ASSOC )) {
$data[] = array(
'LATITUD' => $row['LATITUD'],
'LONGITUD' => $row['LONGITUD'],
'ASUNTO' => $row['ASUNTO'],
);
}
// now we echo this variable, 1 variable containing all the data
$data_string = json_encode($data); // this turns php arrays into a javascript-readable object
echo 'var my_data = ' . $data_string .';'; // notice which ; is for javascript and which is for php
?>
var my_data will be something like this (I'll insert some locations in Brussels):
var my_data = [{"LATITUD":"50.89496405015655","LONGITUD":"4.341537103056892","ASUNTO":"Atomium"},{"LATITUD":"50.84501941894387","LONGITUD":"4.349947169423087","ASUNTO":"Manneken Pis"},{"LATITUD":"50.83847065124941","LONGITUD":"4.376028969883903","ASUNTO":"European Parliament"}];
Now the javascript. How do you use infowindows? I'll use my_data hard coded, so you can copy/paste this code and test the javascript.
don't forget your API key
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 90%;
}
</style>
<div id="map"></div>
<script>
var my_data = [{"LATITUD":"50.89496405015655","LONGITUD":"4.341537103056892","ASUNTO":"Atomium"},{"LATITUD":"50.84501941894387","LONGITUD":"4.349947169423087","ASUNTO":"Manneken Pis"},{"LATITUD":"50.83847065124941","LONGITUD":"4.376028969883903","ASUNTO":"European Parliament"}];
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.869754630095834, lng: 4.353812903165801},
zoom: 12
});
for(var i=0; i<my_data.length; i++) {
// marker
var position = {lat: Number(my_data[i].LATITUD), lng: Number(my_data[i].LONGITUD)};
var marker = new google.maps.Marker({
position: position,
title: my_data[i].ASUNTO,
map: map
});
// infowindow
var infowindow = new google.maps.InfoWindow({
content: my_data[i].ASUNTO,
map: map,
position: position
});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?callback=initMap" async defer></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", "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
I wanna be able to dynamically generate the info for each info window using the php for loop i created due to certain variables in locations[i][3] so it will dynamically pull the information on each pass and i can simply assign it. but for some reason if i try to insert this. the code generates fine ... on the source page... but the map wont even load.. does anyone have a fix for this... and to help make it work... MUCH THX in ADVANCE!! the info has been dynamically pulled in a seperate script the $vars are just used for the count to pull the information from the individual arrays. the map markers generate fine with the lats and lng's its that [i][3] part of the location array thats being funky and -- ps. yes the $vars in the code have been set to zero again. but thats in the side script. so it DOES pull all the proper info. for the [3] string - the map just does not generate in the array.
'<'script type="text/javascript">
//PHP - Lat,Lng ARRAY
var locations = [
php code <?php
$x = 0; $i = 0; $j = 0;
for($aa = 0; $aa < $count; $aa++) {
echo "['" . $business_name[$x] . "'," . $lat[$i] . "," . $lng[$j] . "," . "<div class='coupon'><div class='ribbon'><div class='ribbon-stitches-top'></div><strong class='ribbon-content'><h1>$deal[$y]</h1></strong><div class='ribbon-stitches-bottom'></div></div><div class='picture_coupon'><img src='$deal_photo[$b]' width='150' height='100' /></div><div class='deal'><center><h1>$deal[$y]</h1>$deal_info[$a]<b>Expires: $deal_expiration[$c]</b></center></div></div>" . "],";
$x++; $i++; $j++; $id++;
}
?> END of PHP CODE
[ , , , ]
//['Maroubra Beach', -33.950198, 151.259302, 6]
];
//PHP - Lat,Lng ARRAY
var map;
function initialize() {
var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// INVERSE CODE PHP DYNAMIC
var infowindow = new google.maps.InfoWindow();
var marker, i;
var image = '../images/map-icons/blue.png';
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,
icon: image
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][3]);
infowindow.open(map, marker);
}
})(marker, i));
}
/* */
// INVERSE CODE PHP DYNAMIC
// GEO LOCATION SET CENTER AND ERROR HANDLING
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.';
}
// GEO LOCATION SET CENTER AND ERROR HANDLING
}
// google.maps.event.addDomListener(window, 'load', initialize);
</script>
FIXED -- unfortunately the echo ""; function doesnt allow anything but ('') on the inside of it to separate divs etc. unfortunately the javascript will not load with anything but STANDARD html inside of it. not PHP's variation.
solution was to set the string with proper html standards ie instead of and used the concatenation operator.
ex:
$content = '<div class="coupon"><div class="ribbon"><div class="ribbon-stitches-top"></div><strong class="ribbon-content"><h1>'.$deal[$y].'</h1></strong><div class="ribbon-stitches-bottom"></div></div><div class="picture_coupon"><img src="'.$deal_photo[$b].'" width="150" height="100" /></div><div class="deal"><center><h1>'.$deal[$y].'</h1>'.$deal_info[$a].'<b>Expires: '.$deal_expiration[$c].'</b></center></div></div>';
and i assigned that to the array loop to look like this
<?php
$x = 0; $i = 0; $j = 0; $y = 0; $z = 0; $a = 0; $b = 0; $c = 0;
for($aa = 0; $aa < $count; $aa++) {
$content = '<div class="coupon"><div class="ribbon"><div class="ribbon-stitches-top"></div><strong class="ribbon-content"><h1>'.$deal[$y].'</h1></strong><div class="ribbon-stitches-bottom"></div></div><div class="picture_coupon"><img src="'.$deal_photo[$b].'" width="150" height="100" /></div><div class="deal"><center><h1>'.$deal[$y].'</h1>'.$deal_info[$a].'<b>Expires: '.$deal_expiration[$c].'</b></center></div></div>';
echo "['" . $business_name[$x] . "'," . $lat[$i] . "," . $lng[$j] . "," . "'$content'" . "],";
$x++; $i++; $j++; $id++; $y++; $z++; $a++; $b++; $c++;
}
?>
i know nothing of javascript when it comes to what it allows for the goog.... so coming to that conclusion hurt my brain more than i could even imagine...