google maps event.addListener with xml - javascript

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

Related

For loop is not placing text in InfoWindows Google Maps API from array

I am running a for loop to go through all countries and place a marker with the GDP from the World Bank API.
I was able to run the for loop and get all the coordinates from Google Maps Geocoding, but I cannot place the text with the GDP value in the InfoWindows.
It is showing only Zimbabwe when you press any marker. Why is that? How can I fix it? Thanks a lot.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(25, 25),
});
var url = 'http://api.worldbank.org/countries/all/indicators/NY.GDP.MKTP.KD.ZG?date=2015&per_page=264&format=jsonp&prefix=Getdata';
var query_url = url;
var script = document.createElement('script');
script.src = query_url;
document.getElementsByTagName('head')[0].appendChild(script);
}
window.Getdata = function(data) {
var country_gdp = data[1].map(function(item) {
return {
country: item.country.value,
value: item.value,
}
});
for (i = 0; i < country_gdp.length; i++) {
GDP_country_growth = country_gdp[i];
var xhttp = new XMLHttpRequest();
xhttp.addEventListener('load', processResponse);
xhttp.open('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=' + GDP_country_growth.country + '&key=YOURAPIKEYHERE');
xhttp.send();
var processResponse = function() {
var coordinates = JSON.parse(this.response);
console.log(coordinates);
var latLng = new google.maps.LatLng(coordinates.results[0].geometry.location.lat, coordinates.results[0].geometry.location.lng);
var contentString = 'The GDP of ' + GDP_country_growth.country + ' is ' + GDP_country_growth.value;
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: map,
contentString: contentString
});
marker.addListener('click', function() {
infowindow.setContent(this.contentString);
infowindow.open(map, this);
map.setCenter(this.getPosition());
});
}
}
}
To solve the association of the infowindow data with the geocoded location, one option is to use function closure (the function below gets closure on GDP_country_growth, the element of the array that is used for the geocoding request):
function processCountry(GDP_country_growth) {
var xhttp = new XMLHttpRequest();
var processResponse = function() {
var coordinates = JSON.parse(this.response);
console.log(coordinates);
var latLng = new google.maps.LatLng(coordinates.results[0].geometry.location.lat, coordinates.results[0].geometry.location.lng);
var contentString = 'The GDP of ' + GDP_country_growth.country + ' is ' + GDP_country_growth.value;
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: map,
contentString: contentString
});
marker.addListener('click', function() {
infowindow.setContent(this.contentString);
infowindow.open(map, this);
map.setCenter(this.getPosition());
});
}
xhttp.addEventListener('load', processResponse);
xhttp.open('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=' + GDP_country_growth.country);
xhttp.send();
}
proof of concept fiddle
code snippet:
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(25, 25),
});
var url = 'http://api.worldbank.org/countries/all/indicators/NY.GDP.MKTP.KD.ZG?date=2015&per_page=264&format=jsonp&prefix=Getdata';
var query_url = url;
var script = document.createElement('script');
script.src = query_url;
document.getElementsByTagName('head')[0].appendChild(script);
}
window.Getdata = function(data) {
var country_gdp = data[1].map(function(item) {
return {
country: item.country.value,
value: item.value,
}
});
for (i = 0; i < country_gdp.length; i++) {
(function(country_info) {
setTimeout(function() {
processCountry(country_info);
}, 1000 * i);
})(country_gdp[i])
}
}
google.maps.event.addDomListener(window, "load", initMap);
function processCountry(GDP_country_growth) {
var xhttp = new XMLHttpRequest();
var processResponse = function() {
var coordinates = JSON.parse(this.response);
console.log(coordinates);
var latLng = new google.maps.LatLng(coordinates.results[0].geometry.location.lat, coordinates.results[0].geometry.location.lng);
var contentString = 'The GDP of ' + GDP_country_growth.country + ' is ' + GDP_country_growth.value;
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
var marker = new google.maps.Marker({
position: latLng,
map: map,
contentString: contentString
});
marker.addListener('click', function() {
infowindow.setContent(this.contentString);
infowindow.open(map, this);
map.setCenter(this.getPosition());
});
}
xhttp.addEventListener('load', processResponse);
xhttp.open('GET', 'https://maps.googleapis.com/maps/api/geocode/json?address=' + GDP_country_growth.country);
xhttp.send();
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Google Maps load from DB with GeoLocation

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.

Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api

doctype html
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
script(src='/javascripts/jquery.min.js')
script(src='http://maps.google.com/maps/api/js?key=AIzaSyD6MCxtDJOnbE1T6Y09k8Uca1rXHTQ3Bqg&v=3.exp&sensor=true&libraries=place‌​s')
script(src='/javascripts/global.js')
h1= title
#loading
p Loading your location
br
#map
input#my-address(type='text')
button#getCords(onclick='codeAddress();') getLat&Long
I write above code in jade template for display the map i.e 'index.jade' and
following file i.e 'global.js' is script file
//Calling the locateme function when the document finishes loading
$(document).ready(function() {
locateMe();
});
//Function to locate the user
var locateMe = function(){
var map_element= $('#map');
if (navigator.geolocation) {
var position= navigator.geolocation.getCurrentPosition(loadMap);
} else {
map_element.innerHTML = "Geolocation is not supported by this browser.";
}
};
//Lets load the mop using the position
var loadMap = function(position) {
var loading= $('#loading');
var latitude=position.coords.latitude;
var longitude=position.coords.longitude;
var myLatlng = new google.maps.LatLng(latitude, longitude);
//Initializing the options for the map
var myOptions = {
center: myLatlng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
//Creating the map in teh DOM
var map_element=document.getElementById("map");
var map = new google.maps.Map(map_element,myOptions);
//Adding markers to it
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'You are here'
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow({
content: "<h2>You are here:</h2>",
//Settingup the maxwidth
maxWidth: 300
});
//Event listener to trigger the marker content
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);});
};
//get lat and log
function codeAddress() {
alert('inside')
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var lat=results[0].geometry.location.lat();
var lng=results[0].geometry.location.lng();
var pyrmont={lat:lat,lng:lng};
var map = new google.maps.Map(document.getElementById("my-address"),{
center:pyrmont,
zoom:15
});
//Adding the Marker content to it
var infowindow = new google.maps.InfoWindow();
alert(infowindow);
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
};
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Uncaught TypeError: Cannot read property 'PlacesService' of undefined in google map api
You are doing Place Search which doesnt return all of the fields that you are using:
http://code.google.com/apis/maps/documentation/javascript/places.html#place_search_responses
In order to get the address, website, etc, you'll also need to call place.getDetails(), passing the Place's reference.
Below is a sample code snippet how to get Places details:
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var request = { reference: place.reference };
service.getDetails(request, function(details, status) {
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(details.name + "<br />" + details.formatted_address +"<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number);
infowindow.open(map, this);
});
});
}

Markers not showing in Google Maps API

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)

Google Maps API V3 Clearing Markers Before Update

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

Categories

Resources