LatLng as an exploded array in Google Maps API - javascript

I'm retrieving a string of LatLng coordinates from a database and used PHP's explode function and stored it in an array. I want to pass the array from PHP to JavaScript. Also, I want the Polygon function to accept the array and draw the coordinates accordingly. I'm currently stumped. :( Please help.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzZfro&sensor=false">
</script>
<script>
function initialize() {
var myLatLng = new google.maps.LatLng(8.5000,125.8333);
var myOptions = {
zoom: 8,
center: myLatLng,
};
var map = new google.maps.Map(document.getElementById("map-canvas"),
myOptions);
var davaoCoordinates = [
new google.maps.LatLng(7.0644,125.6078),
new google.maps.LatLng(8.4833,124.6500),
new google.maps.LatLng(8.5000,125.8333)
];
var davaoCity = new google.maps.Polygon({
path: davaoCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
davaoCity.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the PHP code:
<?php
$connect = mysql_connect("localhost", "root", "");
mysql_select_db('capdb');
if (mysqli_connect_errno()){
echo "Failed to connect to database: " . mysqli_connect_error();
}
$query ="SELECT cap_info.event, cap_info.sendername, cap_info.urgency, cap_area.polygon
FROM cap_info
INNER JOIN cap_area ON cap_info.capid = cap_area.capid
WHERE cap_info.capid =1";
$result = mysql_query($query);
if (!$result){
echo "Query Error." . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0){
echo "No rows found, nothing to print.";
exit;
}
while ($row = mysql_fetch_array($result)){
$event = $row['event'];
$sender = $row['sendername'];
$urgency = $row['urgency'];
$polygon = $row['polygon']."\n";
}
$coordsArray = explode (" ", $polygon);
$count = sizeof($coordsArray);
//$n=0;
//while ($n < $count){
//echo $coordsArray[$n];
//$n++;
//}
?>

Not sure what your array looks like, but, In your php, just create the points for the poly with something like below. That should at least help point you in the right direction.
$poly = "";
// loop all values
foreach($array as $v) {
$poly .= "new google.maps.LatLng(".$v."),\n";
}
// add first item from array to close poly
$poly .= "new google.maps.LatLng(".$array[0].")";
Then, in your javascript, just echo the values where you need them
var map = new google.maps.Map(document.getElementById("map-canvas"),myOptions);
var davaoCoordinates = [
<?php echo $poly; ?>
];

Related

I am having some problems with transfering a javascript object to a php file and getting that object in a MySQL database

I want to put 3 variables in a javascript object and transfer that object to a php file, then upload it to the database. The result is a table filled with zeroes instead of floats and empty text fields. I guess that somewhere along the way the values of that object get nullified.
For now I only want to upload the 2 coordinate variables: lat and lng using the obj object. The console confirms that the object is filled with the correct values so my guess is that the problem lies somewhere within the php, because when I open the php page it says the following: "NULL New record created successfully".
Here is the javascript code:
var pressed = false;
var markerPos;
var clickCoords = {};
var xx,yy;
var x,y,descr;
var objStr;
var obj = new Object;
var description;
var map;
function getval()
{
description = document.getElementById("type").value;
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
map.addListener('mousemove', function(event) {
markerPos = {lat: event.latLng.lat(), lng:event.latLng.lng()}
});
map.addListener('click',function()
{
if (pressed)
{
var marker = new google.maps.Marker({position: markerPos, map: map});
Object.assign(obj,markerPos);
console.log(markerPos.lat);
pressed=false;
}
});
objStr = JSON.stringify(obj);
map.addListener("click",function()
{
console.log(obj.lat);
console.log(obj.lng);
console.log(obj);
});
}
function upload()
{
getval();
$.ajax({
url: "map.php",
method: "post",
data: {obj:objStr},
success: function(res)
{
console.log(objStr);
}
});
}
PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "map";
$obj = isset($_POST['obj']);
$decoded = json_decode($obj,true);
var_dump($decoded);
$lat = $decoded['lat'];
$lng = $decoded['lng'];
$descr = $decoded['descr'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO mapinfo (lat,lng,descr)
VALUES ('$lat','$lng','$descr')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

xml markers have wrong encoding

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.

PHP Display multi-dimentional array value on google map

Can anyone help me, I am very new to PHP, maybe the answer was very obvious.
I store users details and postcodes in the database, then I need to display the postcodes as markers on the google map using javascript (this was working).
But I was trying to display each user data on google map's info window, I am only be able to display the last row of the result, so all info windows were display the same record, not the individual data to that postcode.
I think I need to combine below two queries, but I don't know how. Because the postcode need to be implode to get "postcode" to show on map.
What I am trying to achieve:
postcode need to be ("AA4 1DD", "AB1 5CD","CC4 1BBs");
infowindow (Fred, 7 street, AA4 1DD);
What I have in the Database:
name Fred Ann John
address 7 street 8 road 4 line
postcode AA4 1DD AB1 5CD CC4 1BB
PHP:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$locations = $conn->prepare("SELECT postcode FROM tbl_data");
$locations->execute();
$lo= $locations->fetchAll(PDO::FETCH_COLUMN);
echo "'". $t = implode(' ,', $lo)."'";// working
//info window
$info_stmt = $conn->prepare("SELECT name, postcode FROM tbl_data, tbl_login WHERE tbl_data.user_id=tbl_login.user_id ");
$info_stmt->execute();
$result = $info_stmt -> fetchAll();
foreach( $result as $row ) {
echo $row[0];
/* echo "<pre>";
echo gettype($row[0]);
echo "</pre>";*/
}
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
die();
}
Javascript:
var addressArray = new Array(<?php echo "'". $t = implode("' ,'", $lo)."'"; ?>); //postcodes working
var geocoder = new google.maps.Geocoder();
for (var i = 0; i < addressArray.length; i++) {
geocoder.geocode( { 'address': addressArray[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: 'Click for more details'
});
//create info window
var infoWindow = new google.maps.InfoWindow({
content: "<p>Name: </p><?php echo $row[0].'<br />'.$row[1]; ?>"
});
Your issue is here:
content: "<p>Food Name: </p><?php echo $row[0].'<br />'.$row[1]; ?>"
You cannot mix JavaScript and PHP like this, and $row does not - or shouldn't - actually exist in this context due to it not being within the foreach statement or - if this is a seperate JS file - you have no corresponding context.
To achieve what you need, I'd suggest using AJAX and setting a GET request to a file which then returns an array which you can then use in your JavaScript.
You can read documentation on this here.
Note, $row should be used like this: $row['ColumnName'] (not just for readability).
For example: echo $row['address'];
Example Code (PHP):
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$locations = $conn->prepare("SELECT postcode FROM tbl_data");
$locations->execute();
$lo= $locations->fetchAll(PDO::FETCH_COLUMN);
echo "'". $t = implode(' ,', $lo)."'";// working
//info window
$info_stmt = $conn->prepare("SELECT name, postcode FROM tbl_data, tbl_login WHERE tbl_data.user_id=tbl_login.user_id ");
$info_stmt->execute();
echo $info_stmt->fetchAll();
} catch(PDOException $e) {
echo "Error: " . $e->getMessage();
}
Then your JavaScript:
$(document).ready(function () {
var output[];
$.get("phpfile.php")
.done(function(data) {
output = data;
});
});
output is now the array of all your results and can be used.

Google map custom marker based on database

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';

Fetch data from database and use it to make markers in Google Maps

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

Categories

Resources