Load Dynamic Google Markers From MySQL - php

I wonder whether someone could help me please.
I'm using the script below to dynamically load Google markers from a MySQL database and the script works fine.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Map My Finds - My Finds Per Location</title>
<link rel="stylesheet" href="myfindsperlocation.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("loadmyfindsperlocation.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var locationid = markers[i].getAttribute("locationid");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var marker = new google.maps.Marker({
map: map,
position: point
});
bounds.extend(point);
map.fitBounds(bounds);
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, 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 onLoad="load()">
<div id="map"></div>
</body>
</html>
You'll see it's a relatively simple form, which calls the data from an external PHP file which is shown in my script here: downloadUrl("loadmyfindsperlocation.php", function(data) {
What I'm now trying to do is incorporate the PHP script into the above, but I can't seem to get the map to load and I suspect it's something to do in calling the file as a URL.
Forgive me for asking, I'm relatively new to PHP an XML, but could someone perhaps tell me please how I could call this without loading it as an external URL.
Many thanks and kind regards

I don't have either your CSS or PHP so I can only guess. Do you see errors in your Javascript console?
What I did was add the following styles and the map loaded, even with the PHP missing and giving me errors.
html, body, #map { margin: 0; padding: 0; height: 100% }
About loading the PHP, it has to be served to return a meaningful XML. You can have a pre-written XML and load that too.

Related

Adding place markers to Google Map

I have this code below which draws a line on a google maps from co-ordinates from an XML file.
However I want it to show the first co-ordinate and the last coordinate with a place marker as well. I managed to do this without drawing the line by following the steps here:
https://developers.google.com/maps/articles/phpsqlajax_v3?csw=1
but can't seem to be able to integrate the 2. i.e Draw the line and have place markers at the start and finish.
I'm sure its just a tiny bit of code I have to add too the code I already have below but I'm wrecking my train trying to work it out. Any help would be greatly appreciated.
<!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 type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<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 point;
var flightPlanCoordinates=new Array();
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(50.431, -3.202),
zoom: 9,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
});
downloadUrl("phpsqlajax_genxml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
flightPlanCoordinates[i]=point;
}
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
});
}
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" style="width: 500px; height: 300px"></div>
</body>
</html>
In the code that you posted above, you are never adding your markers to the map, which is done with the following code:
var marker = new google.maps.Marker({
map: map, //The Map Object
position: point //The location of the Marker
});
You would want to put this statement into your for loop as you iterate through the GPS points, and if it is the first iteration or the last iteration through the loop, than add your marker. You can than draw your polyline after the loop like you are doing in your posted example.

Drawing markers on a google map starting from a php array

All right, I'll try to explain my problem as clearly as I can. I already tried a lot of possible solution but never happen to find the right one.
I also want to say this is a tutorial for me, i am just a beginner in combining JS, PHP and GMAPv3 APIs.
I hope that someone can help me in solving this.
That being said, here is my code with a few lines to explain what i want to do.
The problem involves 3 main files.
1) process.php (this file generates an array of coordinates)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>MyTest</title>
<link rel="stylesheet" type="text/css" href="css/content.css" />
<script type="text/JavaScript" src="js/gmapinit.js"></script>
</head>
<body>
<?php
...after some lines of code i build this...
$myarray = ...;
...and here i move to the second file
echo "<input type=\"button\" value=\"Next!\" onClick=\"location.href='map.html'\">";
?>
</body>
2) map.html (this file is responsible for drawing the map on the screen)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<title>MyTest</title>
<link rel=stylesheet type="text/css" href="css/googlemap.css" />
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCbNM4y2fJ4AdCoXcWW-sGXPl5nXaJogPA&sensor=false">
</script>
<script type="text/JavaScript" src="js/gmapinit.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
</head>
<body onLoad="init_map_and_markers()">
<div id="map_canvas">
</div>
</body>
2) gmapinit.js (the javascript file that builds the map and "should" get the array as parameter to draw markers accordingly)
function init_map_and_markers() {
var global_markers = [];
var infowindow = new google.maps.InfoWindow({});
var latlng = new google.maps.LatLng(27.059126, -41.044922);
var myOptions = {
zoom: 3,
center: latlng,
mapTypeId: google.maps.MapTypeId.HYBRID
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
//Of course here myarray is not defined but the point is making it available here so i can loop through it and place my markers!
for (var i = 0; i < markers.length; i++) {
for(var count = myarray.length - 1; count >= 0; --count) {
var o = myarray[count];
var lat = parseFloat(o.lat);
var lng = parseFloat(o.lng);
var markerdata = o.user;
var myLatlng = new google.maps.LatLng(lat, lng);
var contentString = "<html><body><div><p><h2>" + markerdata + "</h2></p></div></body></html>";
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: "Coordinates: " + lat + " , " + lng + " | Marker Data: " + markerdata
});
marker['infowindow'] = contentString;
global_markers[i] = marker;
google.maps.event.addListener(global_markers[i], 'click', function() {
infowindow.setContent(this['infowindow']);
infowindow.open(map, this);
});
}
}
}
So the main question is, how can i pass $myarray from process.php to map.html making it available to gmapinit.js???
I am asking this avoiding to write down all code-tests i did because maybe my all thinking is wrong...that's why i am writing down the most "clean" code i got.
Code possible solutions would be much appreciated, and don't hesitate to ask for details if i missed something.
Thanks a lot.
you may use the markers as argument for init_map_and_markers()
<body onLoad="init_map_and_markers(<?php echo json_encode($phpArrayMarkersDefinition); ?>)">
..then you may access this array inside the function:
function init_map_and_markers(markers)
{
//....
for(var i=0;i<markers.length;++i)
{
//create the markers here
}
//....
}

Calling a JavaScript function in PHP for Google Map

hopefully you can help me. I have read a lot of forums regarding this but still cannot get what I wanted. I'm using PHP/MySQL to run my system. I already had a code in JavaScript that will allow the user to add a place and the system can add that place in the Google Map (embedded in my site) as a marker. Now, what I wanted is to add the coordinates of that new place in my database and then my map will just get the markers from the database for adding in the map.
Currently, what I did is to get the latitude and longitude of the added place from the javascript then was able to pass them to my php script within the same file. The latitude and longitude can be added in my database but I do not know now how to go back again to JavaScript so that I can add my markers.
What is the best way to do this? Is/Are there better approaches to solve this?
<?php
$marker = array();
if(isset($_GET['set'])){
$lat = $_GET['lat'];
$long = $_GET['longi'];
$newadd = $_GET['newAdd'];
$connect = mysql_connect("localhost","root","");
mysql_select_db("mapping");
$query=mysql_query("INSERT INTO markers VALUES('','','$newadd','$lat','$long','')");
}
?>
My JavaScript to place markers
function addMarkers(){
var tempMarker;
var tabs = [];
var blueIcon = new GIcon(G_DEFAULT_ICON);
blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/green-dot.png";
// Set up our GMarkerOptions object
markerOptions = { icon:blueIcon };
// for loop get data from db and loop it
tempMarker = new GMarker(tempLatLng,markerOptions);
//if(tabs.length==0){
tabs[ctr] = [new GInfoWindowTab('Greetings','Hi! Welcome'), new GInfoWindowTab('My Info',tempMarker.getLatLng().toString())];
//}
tabInfoWindow(tempMarker,tabs, ctr);
markerArray.push(tempMarker);
displayMarkers();
}
}
Thanks!
Using jquery you can post the data in an ajax request and continue adding the markers in the success handler.
var location = {lat:56, lng:67, name:"my_place"};
$.ajax({
url: "save_place.php",
data: location,
dataType:"json",
success: function(response){
if(response.success){
// add marker to map here
}else{
alert("Error adding location to database");
}
},
error:function(){
alert("Error in connecting to server");
}
});
EDIT:
From your comments, I understand what you need is this one:
<?php
$lat = isset($_GET['lat']) ? $_GET['lat'] : 0;
$long = isset($_GET['longi']) ? $_GET['longi'] : 0;
$newadd = isset($_GET['newAdd']) ? $_GET['newAdd'] : "";
?>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type='text/javascript' src="http://maps.google.com/maps/api/js?sensor=false&.js"></script>
<style type='text/css'>
#map {
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div id="map"></div>
<script type='text/javascript'>//<![CDATA[
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(55, 11),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function addMarker(lat, lng, newAdd) {
alert(" Adding marker " + lat + "," + lng);
this.lat = lat;
this.long = lng;
var location = new google.maps.LatLng(lat, long);
var marker = new google.maps.Marker({
position: location,
title: name,
map: map,
draggable: true
});
map.setCenter(location);
}
<?php
echo "addMarker($lat, $long, '$newadd')";
?>
</script>
</body>
</html>
url : http://<domain>/test.php?lat=40.735812&longi=-74.001389&newAdd=
Well what I do is have a endpoint on the PHP side that I can ask for the markers. Then when my map has loaded I will make a call to get them and then add them on:
$.post('/server/getMarkers',{},function(markers) {
for(var i=0; i < markers.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(marker[i].latitude, marker[i].longitude),
id:marker[i].id
});
google.maps.event.addListener(marker, "click", function() {
//request data for this.id to show in info window if needed
});
}
});
The getMarkers method on the PHP side could look something like this
public function getMarkers() {
/* fetch an array of markers details from the db by any means... */
$markers = getMarkersFromDB();
foreach ($markers as $key=> $marker) {
$payload[$key]['latitude'] = $marker->latitude;
$payload[$key]['longitude'] = $marker->longitude;
$payload[$key]['id'] = $marker->id;
}
echo json_encode($payload);
}

Jquery load() a html file which contains JavaScript

I have a big dilema. I want to load a .html file which contains javascript(google maps) code to render the div inside it.
maps.html look like this :
<script type="text/javascript">
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var hash = getUrlVars();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(hash['lat'],hash['lng']),
zoom: 14,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("xmlout_carol.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length+1; i++) {
var name = markers[i].getAttribute("nume");
var address = markers[i].getAttribute("adresa");
var type = markers[i].getAttribute("id");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<font face='Tahoma' style='font-size:12px;'><div style='min-width:230px;'><b>" + name + "</b> <br/>" + address +"<a target='_top' href='../statii.php?id=" + type + "'><img style='float:right; border:0px; margin-left: 40px;' src='go.png' /></a><div/></font>";
var tip = markers[i].getAttribute("tip");
var icon = customIcons[tip] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
// shadow: 'shaddow.png'
//shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'mouseover', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
google.maps.event.addListener(map, 'click', function() {
infoWindow.close(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>
<body onload="load()">
<div id="map" style="width: 900px; height: 500px"></div>
</body>
this script render the map to the div.map
What i want to do is to load this .html into a div that is contained in another .php file like this :
$("div#insert_here").load("maps.html?lat=xxx&long=yyy");
It output the div contained in maps.html but with no map no java.
So the question is... How do I load a .html file using jquery in another .php file if the .html file already contains javascripts to output data to the div in .html file ???
Thanks a lot !
Instead of loading a file which has both HTML and JavaScript in it, can you load the JavaScript with the page initially, make an ajax call for the HTML, and call the JavaScript once the ajax request is complete? This will solve a lot of headaches with this issue.
As the others said, load JS particularly, or do the eval() function ;).
That parses the JS and makes it possible to be executed initially.
I dont use load and get much it almost always seems better to use $.ajax or $.post (more flexibility, I also suggest calling json and using the dataType:"json". Again more flexible).
Use callbacks after success to run the javascript you need once the ajaxed html is loaded into the page. You call use beforeSend to load script you need (although unless there is a good reason just add those scripts to the page along with everything else (more robust/cacheable)).
If google_statii.js needs dynamic variables one way would be use hidden inputs on the page with values populated server side and then call them within the script.
ie. var x = $("input#myHiddenVariable");

Help creating Multiple InfoWindows using Google Maps

I am creating a php page that loads cordinates from a mysql table and use them to create markers on a google map. It works fine. I also added Info Window but the problem is that the content on the info window for all the markers is showing the content meant for the last marker in the table. Below is the code:
<?php
include("php/db.php");
$db = new dbAccess($db_host,$db_user,$db_pass, $db_db, true);
$db->query("select * from tbl_gps;", false);
while($row_gps = $db->fetchrow()){
$gps_list .= "['".$row_gps['gps_title']."', ".$row_gps['lat_dec'].", ".$row_gps['long_dec'].", ".$row_gps['gps_order']."],\n";
}
?>
<!DOCTYPE html>
<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>Aerial View Of Federal Polytechnic Bauchi</title>
<link href="http://code.google.com/apis/maps/documentation/javascript/examples/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var myOptions = {
zoom: 17,
center: new google.maps.LatLng(10.256817, 9.771996),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
var map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
setMarkers(map, struct);
}
/**
* Data for the markers consisting of a name, a LatLng and a zIndex for
* the order in which these markers should display on top of each
* other.
*/
var struct = [
<?php echo $gps_list; ?>
];
var markers = new Array();
function setMarkers(map, locations) {
var infowindow = null;
for (var i = 0; i < locations.length; i++) {
var location = locations[i];
var myLatLng = new google.maps.LatLng(location[1], location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: location[0],
zIndex: location[3]
});
/* now inside your initialise function */
infowindow = new google.maps.InfoWindow({
content: "holding..."
});
google.maps.event.addListener(marker, 'click', function () {
// where I have added .html to the marker object.
infowindow.setContent(location[0]);
infowindow.open(map, this);
});
}
}
</script>
</head>
<body style="background-color:#000" onload="initialize()">
<div id="map_canvas" style="height:95%; width:100%"></div>
</body>
</html>
Well, your code has the problem with javascript closure. It's the common problem when attaching event listeners in the loop. Try to understand and follow http://code.google.com/apis/maps/documentation/javascript/examples/event-closure.html.

Categories