I have searched and searched for an answer with no luck. I can get the xml data to display fine and it appears that my markers refresh but just wont remove the previous one so they stack up. Any help would be great! I just need to remove the markers before the new ones appear. Thanks!
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//<![CDATA[
var markersArray = [];
var customIcons = {
restaurant: {
icon: 'pin.png',
shadow: ''
},
bar: {
icon: 'loc1.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
airport: {
icon: 'loc2.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(37.0923204, -95.9042496),
zoom: 5,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
setInterval(function() {
downloadUrl("phpsqlajax_genxmlall.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
resetMarkers(markersArray)
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var amount = markers[i].getAttribute("amount");
var time = markers[i].getAttribute("time");
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/>" + address + "<br/>$" + amount + " at " + time;
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);
}
});
}, 5000);
}
function resetMarkers(arr){
for (var i=0;i<arr.length; i++){
arr[i].setMap(null);
}
//reset the main marker array for the next call
arr=[];
}
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: 1400px; height: 800px"></div>
</body>
The problem is, you are not adding your markers to markerArray, it stays empty, so there is nothing to remove when you call resetMarkers
After creating the marker, add it to markerArray:
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
markerArray.push(marker);
Related
So I have some working code which fetches results from my DB and displays them on a Google map. I also have some code which uses my location to place a marker on a Google map.
My issue is that when I add them together the page loads the results from the DB then I accept geoloaction and it centers the map to my location but doesn't display my marker and also removes the markers for the DB results.
Here is the DB result code:
<!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>PHP/MySQL & Google Maps Example</title>
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY"
type="text/javascript"></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 map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.6145, -122.3418),
zoom: 13,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("/Models/phpsqlajax_genxml2.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/>" + 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" style="width: 500px; height: 300px"></div>
</body>
</html>
This is my geolocation code:
// Check if user support geo-location
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
var map = new google.maps.Map(document.getElementById('nearMeMap'), {
zoom: 11,
scaleControl: false,
scrollwheel: false,
center: geolocpoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
// Place a marker
var geolocation = new google.maps.Marker({
position: geolocpoint,
map: map,
title: 'Your Location',
icon: 'https://mt.google.com/vt/icon?psize=20&font=fonts/Roboto-Regular.ttf&color=ff330000&name=icons/spotlight/spotlight-waypoint-blue.png&ax=44&ay=48&scale=1&text=%E2%80%A2'
});
});
}
Also I get this in the console:
ReferenceError: locations is not defined
for (i = 0; i < locations.length; i++) {
As the ReferenceError already says, you do not have the variable locations defined in your geolocation code.
I have followed a number of google articles explaining how to use Google maps, along with marker clustering as well.
However i have been trying to integrate Place Search Box into the code. I have got the place box looking correct and autofilling. Its just, for some reason, not zooming to the location. I think there's just a simple issue that im not seeing. I have put in my code below. Any help would be much appreciated.
function load() {
var cluster = [];
infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(51.843791, -2.197041),
zoom: 10,
mapTypeId: 'hybrid'
});
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
var infowindow = new google.maps.InfoWindow();
// Read the data from example.xml
downloadUrl("../phpsqlajax_genxml3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
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/>" + address + "</b> <br/>" + type;
var icon = customIcons[type] || {};
// create the marker
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
google.maps.event.addListener(marker, 'click', (function(marker, i, html) {
return function() {
infowindow.setContent('<div style=height:80px;overflow:none>'+html+'</div>');
infowindow.open(map, marker);
}
})(marker, i, html));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster);
});
}
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()">
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
</body>
</html>
thanks for the comment. I have tried to insert that missing piece into the code, however it still not zooming to the selected location. Is there anything i need to take out?
function load() {
var cluster = [];
infoWindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(51.843791, -2.197041),
zoom: 10,
mapTypeId: 'hybrid'
});
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
var infowindow = new google.maps.InfoWindow();
// Read the data from example.xml
downloadUrl("../phpsqlajax_genxml3.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
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/>" + address + "</b> <br/>" + type;
var icon = customIcons[type] || {};
// create the marker
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
google.maps.event.addListener(marker, 'click', (function(marker, i, html) {
return function() {
infowindow.setContent('<div style=height:80px;overflow:none>'+html+'</div>');
infowindow.open(map, marker);
}
})(marker, i, html));
cluster.push(marker);
}
var mc = new MarkerClusterer(map,cluster);
});
}
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()">
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
</body>
</html>
You are missing this code from the example (the part that does something with the results on the map):
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
I have just loaded the following code into my webpage and after many hours of troubleshooting, I can't get the Markers to show up?
I have confirmed that the parsing php file is working.
Javascript:
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
var customIcons = {
accom: {
icon: 'images/google_map_icon_green.png'
},
food: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png'
}
};
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(
<?php if ($_COOKIE[company] == 'ch') { echo $ch[hls_lat].", ".$ch[hls_long]; } elseif ($_COOKIE[company] == 'shc') { echo $shc[hls_lat].", ".$shc[hls_long]; } elseif ($_COOKIE[company] == 'lmh') { echo $lmh[hls_lat].", ".$lmh[hls_long]; }?>),
zoom: 12,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
var infoWindow = new google.maps.InfoWindow;
downloadUrl("required/xml_parse.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 icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
SetMap: map_canvas,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map_canvas, infoWindow, html);
}
});
function bindInfoWindow(marker, map_canvas, 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>
HTML:
<br />
<div class="inner-article-header"><h2>Map of Locations</h2></div>
<div id="map_canvas" style="height:565px; width:754px; margin:2px;"></div>
</div>
This is incorrect:
SetMap: map_canvas,
Should be (see MarkerOptions in the documentation):
map: map,
corrected marker constructor:
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
Add the parsing of the XML into the initialize function, so map is valid when you add the markers:
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(0,0),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
}
var map = new google.maps.Map(mapCanvas, mapOptions);
downloadUrl("example.xml", 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 icao = markers[i].getAttribute("icao");
var type = markers[i].getAttribute("type");
var elev = markers[i].getAttribute("elev");
var conname = markers[i].getAttribute("contactname");
var connum = markers[i].getAttribute("contactnum");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> - " + icao + "<br/>" + conname + " - " + connum;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
working example (using one of my existing xml files, since you didn't provide any example data)
You have additional problems with the call to bindInfoWindow and its definition (map_canvas, should be map)
I am working on a dealerlocator with google maps. The problem is that when I click on a icon the infowindow opens the wrong window. I use a xml import. Everything is going well until the infowindow.
see website https://www.turbho.com/dealerview.php
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD2maN7CjzWtwI6yuHj8lX078NzV0Ywkg0&sensor=false"></script>
{literal}
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 12,
mapTypeId: 'roadmap'
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Try HTML5 geolocation
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,
panControl: true,
zoomControl: true,
scaleControl: true,
content: 'U bent nu hier.'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesnt support Geolocation
handleNoGeolocation(false);
}
var image = 'https://turbho.com/img/logoturbhogooglesmall.png';
// Change this depending on the name of your PHP file
downloadUrl("xml/datacomplete.xml", 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 zipcode = markers[i].getAttribute("zipcode");
var town = markers[i].getAttribute("town");
var anchor = markers[i].getAttribute("anchor");
var website = markers[i].getAttribute("website");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<span style='font-size:12px;'><b>" +
name + "</b> <br />" +
address + "<br />" +
zipcode + " " + town + "<br /><br />" +
website + "<br /><br />" +
anchor + "</span>";
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image
});
var infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(marker, 'click', function () {
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() {}
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>
{/literal}
<div id="map-canvas"></div>
The problem is solved. I used a function see below and that worked for me.
function add_marker(latlng, title, box_html, image) {
//create the global instance of infoWindow
if (!window.infowindow) {
window.infowindow = new google.maps.InfoWindow();
}
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: title,
icon: image
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.close();
infowindow.setContent(box_html);
infowindow.open(map, this)
});
return marker;
}
Thanx for the help
Ruud
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 :)