google map marker from database using php sql - javascript

i have this code to populate markers from database on google map , but it's is not working ,the xml file is perfectly working , i referred to https://developers.google.com/maps/articles/phpsqlajax_v3, but of no use.
markers.php code
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jainmunilocator";
$connection=mysqli_connect($servername, $username, $password, $dbname);;
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT name,id,lat,lng FROM muni_location,munishri WHERE mid=id";
header('Content-Type: application/xml');
$result=mysqli_query($connection,$sql);
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result)){
if(isset($row['id'])){ $id = $row['id']; }
if(isset($row['name'])){ $name = $row['name']; }
if(isset($row['lat'])){ $lat = $row['lat']; }
if(isset($row['lng'])){ $lng = $row['lng']; }
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("id",$id);
$newnode->setAttribute("name", $name);
$newnode->setAttribute("lat", $lat);
$newnode->setAttribute("lng", $lng);
}
}
echo $dom->saveXML();
?>
*GOOGLE MAP MARKER CODE**
<!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="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(22.6145,77.3418),
zoom: 7,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
var gm_marker = new Array();
// Change this depending on the name of your PHP file
downloadUrl("markers.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var id = markers[i].getAttribute("id");
var name = markers[i].getAttribute("name");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
//var html = "<b>" + name + "</b> <br/>" + id;
var html = name;
var icon = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
var marker = new google.maps.Marker({
map: map,
position: point,
title: name
});
addMarker(point,name);
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
//stackoverflow
function addMarker(latLng, contentstr) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({
content: contentstr
});
});
gm_markers.push(marker);
}
setAllmap(map);
function setAllMap(map) {
for (var i = 0; i < gm_markers.length; i++) {
gm_markers[i].setMap(map);
}
function showMarkers() { setAllMap(map);}
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-canvas-show" style="width: 100%; height: 300px;"></div>
</body>
</html>

There are 2 elements that I think are essential, which I don't see in your code. This is from my source and I'm including them here to show the concepts. You can implement this type of thing within your for loop or break out into functions. I prefer functions, so I did it this way.
First, I would confirm that your marker array is not length 0--that's an easy sanity check--make sure you have markers to load.
Build the Google Map marker stack
While there are markers...
Create the marker with new
Create the listener with new
Push the marker into Google's marker object as an array of marker objects
// Add a marker to the map and push to the array.
function addMarker(latLng, contentstr) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({
content: contentstr
});
});
gm_markers.push(marker);
}
To show the markers assign the marker to the map
Associate each marker from the array to your map canvas.
// Sets the map on all markers in the array.
function setAllMap(map) {
for (var i = 0; i < gm_markers.length; i++) {
gm_markers[i].setMap(map);
}
To clear the Google Map markers (off)
To reinforce the concept. To clear the markers unplug the map markers object array from your map object.
// Removes the markers from the map, but keeps them in the array.
function clearMarkers() {
setAllMap(null);
}
To show already loaded markers (on)
// Shows any markers currently in the array.
function showMarkers() {
setAllMap(map);
}
In the view
Showing the map with the markers
<div id="map-canvas-show" style="width: 100%; height: 300px;"></div>
Debugging steps (added)
I would suggest first to confirm that valid coordinates are being loaded into the marker vars in your php. In fact, I would start with a test with one single marker. Put in debug statements to show your lat and lng. This is essential. Confirm valid marker data from php into your js.
Then, you need to confirm that those markers are within the visible range of your Google map. Are the markers there, just not visible? To help, I would suggest that you make Google map zoomed way out - scale it so you'd see a marker halfway around the world.

Related

PHP Google Map Real-Time Tracking

I'm completely new to programming. I just learned PHP and am now trying to do real-time tracking using Google Maps.
When I run my script I get a map with the right center location but no trip.
The script is based on:
https://developers.google.com/maps/articles/phpsqlajax_v3?csw=1
I added a call to setTimeout() for real-time tracking, which is now commented out in case its causing a problem.
I tested my newTripXml.php script and it worked stand-alone. But when I put an echo statement into it, I see that the code below is never calling it. Its in the same directory as the php file below, which I am running in XAMPP.
I'd really appreciate some help. Thanks.
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/includes.php');
session_start();
if(Nav::getInstance()->loggedIn())
if(array_key_exists(DBAtr::TripID,$_GET))
$tripID= $_GET[DBAtr::TripID];
echo "DRAW MAP!!!!!!!!!!!!!!!!!!!<br/>";
$tripID=1;
if(!isset($tripID)) { //logout
Nav::getInstance()->logOut();
exit;
}
?>
<!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 echo "Trip Report"; ?></title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript">
var markersArray = []; //global markers array
var map;
/*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'
}*/
//load new map
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center : new google.maps.LatLng('33.347', '248.161'),
zoom : 13,
mapTypeId : 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
//first call to get & process inital data
downloadUrl("newTripXml.php",processXML);
}
//update map
function processXML(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
//clear markers before you start drawing new ones
resetMarkers(markersArray)
for(var i=0; i<markers.length; i++) {
var host = markers[i].getAttribute("host");
var type = markers[i].getAttribute("active");
var lastupdate = markers[i].getAttribute("lastupdate");
var point = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + "Host: </b>" + host + "<br>" + "<b>Last Updated: </b>" + lastupdate + "<br>";
var icon = customIcons[type] || {}; //?!!!
var marker = new google.maps.Marker({
map : map,
position : point,
icon : icon.icon,
shadow : icon.shadow
});
//store marker object in a new array
markersArray.push(marker);
bindInfoWindow(marker, map, infoWindow, html);
}
/*
set timeout after you finished processing & displaying first lot of markers
requests on the server can take some time, so you want to make another one
only when the first one is completed
*/
/*setTimeout(function() {
downloadUrl("newTripXml.php",processXML);
}, 5000);*/
}
//clear existing markers from map
function resetMarkers(arr) {
for(var i=0; i<arr.length; i++){
arr[i].setMap(null);
}
arr=[]; //reset marker array for next call
}
//bind info window
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
//download url
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);
}
</script>
</head>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>

Every infowindow is displaying the same data maps api v3

I am really stuck on something. Every map marker's infowindow is displaying the same info. It seems to be the content at the end of an array that i use to store content nodes every time. I am pretty sure it is because the infowindow is not being attached to the proper marker
var markers = [];
var contentArray = [];
var titleArray = [];
var latlngArray = [];
var map;
//var infowindow;
var concert;
function defaultMap()
{
//Latitude: 38
//Longitude: -97
//window.alert("inside function");
var mapOptions = {
center:new google.maps.LatLng(38,-97),
zoom:4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"),
mapOptions);
// window.alert("addMarkers the size of contentArray is: "+contentArray.length);
//window.alert("addMarkers the size of the titleArray is: "+titleArray.length);
// window.alert("addMarkers the size of the latLongArray is: "+latlngArray.length);
//for(var i =0;i<2;i++)
//{
// if(i == 0)
// {
// marker = new google.maps.Marker({
// position: new google.maps.LatLng(37.8172784,-96.8909115),
// map:map
// });
// markers.push(marker);
// }
// else
// {
// marker = new google.maps.Marker({
// position: new google.maps.LatLng(37.8172973,-96.8766355),
// map:map
// });
// markers.push(marker);
// }
// //markers[0] = new google.maps.LatLng(37.8172784,-96.8909115);
// //markers[1] = new google.maps.LatLng(37.8172973,-96.8766355);
//
//}
//addMarkers();
}
//function
//
//{
//infowindow = new google.maps.InfoWindow({
//content:list
//});
//google.maps.event.addListener(marker,'click',function(){
// infowindow.open(map,marker);
//});
function addMarkers()
{
//console.dir(contentArray[contentArray.length-1]);
for(var i = 0;i <10;i++)
{
if(i == 0)
{
//window.alert("i = "+i);
console.log(latlngArray[i]);
var marker = new google.maps.Marker({
position:latlngArray[i],
animation:google.maps.Animation.DROP,
icon:'./images/club.png',
title:titleArray[i],
map:map
});
//marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
});
google.maps.event.addListener(marker,'click',function()
{
//console.log(infowindow.getContent());
infowindow.setContent(contentArray[i]);
infowindow.open(map,this);
});
markers.push(marker);
}
else
{
console.log(latlngArray[i]);
var marker = new google.maps.Marker({
position:latlngArray[i],
animation:google.maps.Animation.DROP,
icon:'./images/restaurant.png',
title:titleArray[i],
map:map
});
var infowindow = new google.maps.InfoWindow({});
//console.log(infowindow.getContent());
google.maps.event.addListener(marker,'click',function()
{
infowindow.setContent(contentArray[i]);
console.log(infowindow.getContent());
infowindow.open(map,this);
});
markers.push(marker);
}
//console.log(i);
//console.log(contentArray[i]);
}
}
The problem is that when the loop ends, i is 10.
Every infowindow displays:
infowindow.setContent(contentArray[i]);
There are two ways to solve the problem:
function closure. Use a createMarker function to associate the infowindow content with the marker. Explained in Mike Williams' v2 tutorial, one of his examples using function closure, translated to v3.
marker member variable containing the content, access it in the click listener by referencing "this". The answer to this similar question may help with this. Here is an example of using a member variable of the marker
This Code is also for all those who want to put multiple Markers on Map retrieved from DB
i am going to paste a Code of live project means working. you can get some help from this.
function latLongCallback(latitutde,longitutde){
var latlng = new google.maps.LatLng(latitutde, longitutde);
var options = {zoom: 4, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById('map'), options);
$.ajax({type: "GET",
dataType: 'json',
url: 'https://www.xyz.com/yourrfolder/markers.php',
success: function(response){
var total=response.length;
var data_array,name,type,address,lat,lon,arrival,departure,notes;
var infowindow = new google.maps.InfoWindow();
for(var i=0; i < total; i++){
data_array=response[i];
name=data_array['name'];
id = data_array['id'];
address=data_array['address'];
arrival=data_array['arrival'];
departure=data_array['departure'];
notes=data_array['notes'];
lat=data_array['lat'];
lon=data_array['lon'];
icon=data_array['icon'];
sc_id=data_array['sc_id'];
var propPos = new google.maps.LatLng(lat,lon);
propMarker = new google.maps.Marker({
position: propPos,
map: map,
icon: icon,
zIndex: 3
});
var contentString = "<div style='font-size:9px;overflow:hidden'>"+name+"<br/><label class='label'>Location :</label> "+address+"<br/><label class='label'>Arrival :</label> "+arrival+"<br/><label class='label'>Departure :</label> "+departure+"<br/><label class='label'>Notes :</label> "+notes + "</div><div style='font-size:9px;overflow:hidden'><a href='#2' onclick="+xx+" class='popup-txt' style='font-size:11px; margin-top:3px;'>Message him</a><a href='#1' onclick="+invite+" class='popup-txt' style='font-size:11px; margin-top:3px; float:right;'>Invite Friend</a></div>";
function bindInfoWindow(marker, map, infowindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(html);
infowindow.open(map, marker);
});
bindInfoWindow(propMarker, map, infowindow, contentString);
}
}
});
return;
}
and here is the marker.php mentioned in above js
<?php
$data=array();
$retrive_marker_query = "your query";
$result = db_execute($retrive_marker_query);
$cnt=0;
while ($row = mysql_fetch_assoc($result)){
$name = $row['name'];
$id = $row['fb_id'];
$sc_id = $row['id'];
$address = $row['location'];
$lat = $row['lat'];
$lon = $row['lon'];
$data[$cnt]['name'] = $name;
$data[$cnt]['id'] = $id;
$data[$cnt]['sc_id'] = $sc_id;
$data[$cnt]['address'] = $address;
$data[$cnt]['lat'] = $lat;
$data[$cnt]['lon'] = $lon;
$cnt++;
}
$data=json_encode($data);
echo($data);
<?

auto zoom/center google maps api?

I am pretty experienced when it come to php mysql, but javascript has got me scratching my head. I am trying to add google maps to my website to show where picture in my database were taken. I got the static google map to work, but it will only display 37 markers due to the url character limitations. I followed the tutorial at google maps api docs, and i have a map that will display all the coordinates for the images in my database. My problem is that i cannot for the life of me figure out how to get the map to auto center and auto zoom to fit all of my markers. my test website for my map is at maptest. I found this tutorial on how to auto center/zoom my map by no matter where i put his code i get errors. this is the code i have for my map that does not auto zoom/center:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>Google Maps AJAX + mySQL/PHP Example</title>
<script src="http://maps.google.com/maps/api/js? key=AIzaSyDnMkDkoCHNE7BG4eobjeMJdWWZtdZvzeg&sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
restaurant: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
bar: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(42.293564,-39.07617),
zoom: 2,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("phpsqlajax_genxml3.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("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>";
//var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
//icon: icon.icon,
//shadow: icon.shadow
});
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" style="width: 600px; height: 400px"></div>
</body>
</html>
Tried this?
var fitToMarkers = function(markers) {
var bounds = new google.maps.LatLngBounds();
var length = markers.length;
for (var i = 0; i < length; i++) {
bounds.extend(new google.maps.LatLng(markers[i].lat, markers[i].lng));
map.fitBounds(bounds);
}
};

How do I update the locations of multiple markers in google maps

I am using google maps api to place markers on a map. The gps coordinates of the markers are stored in a mySQL database. I have been able to create the markers however the locations will constantly changing so I was wondering how I would go about updating the markers' locations so that the markers will move across the map. Here is my code so far:
<!DOCTYPE html>
<html>
<head><title>Map</title>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0px; padding: 0px }
#map_canvas { height: 100% }
</style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(36.9947935, -122.0622702);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var image = new google.maps.MarkerImage('busIcon.png',
// The image size
new google.maps.Size(44, 46),
// The origin
new google.maps.Point(0,0),
// The anchor
new google.maps.Point(22, 23));
var shadow = new google.maps.MarkerImage('busIcon_shadow.png',
new google.maps.Size(58, 46),
new google.maps.Point(0,0),
new google.maps.Point(22, 23)
);
var shape = {
coord: [1, 1, 1, 45, 43, 45, 43 , 1],
type: 'poly'
};
var markers = [
<?php
// Make a MySQL Connection
mysql_connect("**********", "**********", "**********") or die(mysql_error());
mysql_select_db("matsallen") or die(mysql_error());
//Get number of rows
$result = mysql_query
(
'SELECT COUNT(*) FROM busTrack AS count'
)
or die(mysql_error());
$row = mysql_fetch_array( $result );
$length = $row["COUNT(*)"];
for ($count = 1; $count <= $length; $count++) {
//Get data from MySQL database
$result = mysql_query
(
'SELECT * FROM busTrack WHERE busID = '.$count
)
or die(mysql_error());
// store the record of the "busTrack" table into $row
$row = mysql_fetch_array( $result );
// Echo the data into the array 'markers'
$output = '{id: "Bus '.$row[busID].'", lat: '.$row[lat].', lng: '.$row[lon].'}';
if ($count != $length) {
$output = $output.',';
};
echo $output;
};
?>
];
for (index in markers) addMarker(map, markers[index]);
function addMarker(map, data) {
//create the markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.id,
icon: image,
shape: shape,
shadow: shadow
});
//create the info windows
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.id;
content.appendChild(title);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
}
}
</script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width:75%; height:75%; margin:10%; allign:center;"></div>
</body>
</html>
To change the location of a marker, call setPosition() on that marker:
marker.setPosition(new google.maps.LatLng(newLat,newLng);
To do this, you will need to save all your markers in an array. Perhaps something like this would work:
var myMarkers = new Array();
for (index in markers) {
myMarker[ markers[index]['id'] ] = addMarker(map, markers[index]);
}
function addMarker(map, data) {
//create the markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.id,
icon: image,
shape: shape,
shadow: shadow
});
//create the info windows
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.id;
content.appendChild(title);
var infowindow = new google.maps.InfoWindow({
content: content
});
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
return marker;
}
Then, when the position of a marker needs to change, hopefully you know the bus ID and can just call:
myMarkers['Bus 47'].setPosition(new google.maps.LatLng(newLat,newLng);
I didn't test the above code so there may be small syntax errors or something, but it should give you the idea.

Open infoWindow of specific marker from outside Google Maps (V3)

I can't seem to get my head around this problem:
I've got a map with (a lot of) markers (companies) that come from a generated XML file. Below the map, I want to show a (non-JavaScript-generated) list of all the companies that are displayed on the map. When I would click a company in the list, the map would pan to that specific marker and open an infoWindow. The thing is that I want the map and the list to be two separate things...
What would be the right way to tackle this problem? Thanks! Important is that all markerinfo is dynamic...
function initialize_member_map(lang) {
var map = new google.maps.Map(document.getElementById("large-map-canvas"), {
center: new google.maps.LatLng(50.85034, 4.35171),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
downloadUrl("/ajax/member-xml-output.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 company = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var uid = markers[i].getAttribute("uid"); // Primary key of company table in MySQL
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + company + "</b> <br/>" + address;
bounds.extend(point);
var marker = new google.maps.Marker({
map: map,
position: point,
uid: uid // Some experiments, wanted to use this to target specific markers...
});
bindInfoWindow(marker, map, infoWindow, html);
}
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
});
}
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() {}
Following the suggestions by Michal, I've tried the following, but am encountering two problems: my console tells me markers[index].getPosition is not a function and the first item in my list shows to be undefined. Can you please help?
//JavaScript Document
var map;
var markers = new Array();
var company_list;
function initialize_member_map(lang) {
map = new google.maps.Map(document.getElementById("large-map-canvas"), {
center: new google.maps.LatLng(50.85034, 4.35171),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("/ajax/member-xml-output.php?country=BE", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var company = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var uid = markers[i].getAttribute("uid");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + company + "</b> <br/>" + address;
bounds.extend(point);
var marker = new google.maps.Marker({
map: map,
position: point,
uid: uid
});
bindInfoWindow(marker, map, infoWindow, html);
company_list += "<div onclick=scrollToMarker(" + i + ")>"+company+"</div>";
}
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
//display company data in html
document.getElementById("company_list").innerHTML = company_list;
});
}
function scrollToMarker(index) {
map.panTo(markers[index].getPosition());
}
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(){
}
You are on the right track. You just need to create a separate global array for your Marker objects and push all created markers to this array. When you write out all your company data to html include a call with the index of the marker executed on click. Below is an example code. I used JSON as my data structure to hold company info instead of XML.
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=yes" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps Scroll to Marker</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
</head>
<body onload="initialize()">
<div id="map_canvas" style="width: 900px;height: 600px;"></div>
<div id="companies"></div>
<script type="text/javascript">
var map;
//JSON of company data - equivalent of your XML
companies = {
"data": [
{
"name": "Company 1",
"lat": 42.166,
"lng": -87.848
},
{
"name": "Company 2",
"lat": 41.8358,
"lng": -87.7128
},
{
"name": "Company 3",
"lat": 41.463,
"lng": -88.870
},
{"name":"Company 4",
"lat":41.809, "lng":-87.790}
]
}
//we will use this to store google map Marker objects
var markers=new Array();
function initialize() {
var chicago = new google.maps.LatLng(41.875696,-87.624207);
var myOptions = {
zoom: 9,
center: chicago,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
listCompanies();
}
function listCompanies() {
html = ""
//loop through all companies
for (i=0;i<companies.data.length;i++) {
//get the maker postion
lat = companies.data[i].lat
lng = companies.data[i].lng
//add google maps marker
marker = new google.maps.Marker({
map:map,
position: new google.maps.LatLng(lat,lng),
title: companies.data[i].name
})
markers.push(marker);
html += "<div onclick=scrollToMarker(" + i + ")>"+companies.data[i].name+"</div>";
}
//display company data in html
document.getElementById("companies").innerHTML =html;
}
function scrollToMarker(index) {
map.panTo(markers[index].getPosition());
}
</script>
</body>
</html>
Ok I added another solution for you - uising your code. This one uses your bindInfWindow function to bind the DOM (HTML) click event to open info window and scroll to marker. Please note that because you are loading companies dynamically the divs (or some other tags) that hold their names and ids must exist in the DOM BEFORE you start binding events to it - so the first function you need to execute is the one that renders companies HTML (not the map init). Please note I have not tested this one as I do not have your data..
//you must write out company divs first
<body onload="showCompanies()">
<script>
//JavaScript Document
var map;
//this is your text data
var markers = new Array();
//you need to create your company list first as we will be binding dom events to it so it must exist before marekrs are initialized
function showCompanies() {
downloadUrl("/ajax/member-xml-output.php?country=BE", function(data) {
var xml = data.responseXML;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var company = markers[i].getAttribute("company");
markerId = "id_"+i;
company_list += "<div id="+markerId+">"+company+"</div>";
}
//display company data in html
document.getElementById("company_list").innerHTML = company_list;
//now you are ready to initialize map
initialize_member_map("lang")
});
}
function initialize_member_map(lang) {
map = new google.maps.Map(document.getElementById("large-map-canvas"), {
center: new google.maps.LatLng(50.85034, 4.35171),
zoom: 13,
mapTypeId: 'roadmap'
});
var xml = data.responseXML;
var bounds = new google.maps.LatLngBounds();
//your company data was read in and is ready to be mapped
for (var i = 0; i < markers.length; i++) {
var infoWindow = new google.maps.InfoWindow;
var company = markers[i].getAttribute("company");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var uid = markers[i].getAttribute("uid");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + company + "</b> <br/>" + address;
bounds.extend(point);
var marker = new google.maps.Marker({
map: map,
position: point,
uid: uid
});
//add the new marker object to the gMarkers array
markerId = "id_"+i;
bindInfoWindow(marker, map, infoWindow, html,markerId);
}
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
}
function scrollToMarker(index) {
map.panTo(markers[index].getPosition());
}
function bindInfoWindow(marker, map, infoWindow, html, markerId) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
//bind onlcick events to the div or other object in html
markerObj = document.getElementById(markerId);
//you can create DOM event listeners for the map
google.maps.event.addDomListener(markerObj, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
map.panTo(marker.getPosition());
});
}
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>
since i cannot remove this answer, I decided to add some notes!
if your xml format is similar to this: http://www.w3schools.com/dom/books.xml
you may access author nodeValue with following lines.
markers = xml.documentElement.getElementsByTagName("book");
for (var i = 0; i < markers.length; i++) {
authors = markers[i].getElementsByTagName('author')[0].innerHTML;
}
hope it helps someone :)

Categories

Resources