Marker Drag Click Event Google Maps - google-maps

I have a google maps and a marker that locates my position , it's a draggable marker with an infowindow.
Here is my code
var marker;
var infowindowPhoto;
var latPosition;
var longPosition;
var newLocationLat;
var newLocationLong;
function initializeMarker()
{
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
var pos = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
latPosition = position.coords.latitude;
longPosition = position.coords.longitude;
//alert("Latitude:"+latPosition);
//alert("Longitude:"+longPosition);
marker = new google.maps.Marker
({
position: pos,
draggable:true,
animation: google.maps.Animation.DROP,
map: map
});
markersArray.push(marker);
google.maps.event.addListener(marker, 'click', function (event)
{
infowindowPhoto.open(map,marker);
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
latPosition = this.getPosition().lat();
longPosition = this.getPosition().lng();
});
google.maps.event.addListener(marker,'dragend', function (event)
{
infowindowPhoto.open(map,marker);
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
newLocationLat = this.getPosition().lat();
newLocationLong = this.getPosition().lng();
});
infowindowPhoto.open(map,marker);
map.setCenter(pos);
},
function()
{
handleNoGeolocation(true);
});
}
else
{
handleNoGeolocation(false);
}
contentString ='<h1 id="firstHeading" class="firstHeading">Uluru</h1>';
infowindowPhoto = new google.maps.InfoWindow
({
content: contentString
});
}
function Alert()
{
alert("Latitude:"+latPosition);
alert("Longitude:"+longPosition);
alert("newLatitude:"+newLocationLat);
alert("newLongitude:"+newLocationLong);
}
The marker first is positioned in my location , if i don't drag the marker it show me in the function alert my position. So in the two fist alert in function aloert it shows me my position and the two other alert are undefined.
Now my problem is that i want when i dont move the marker that this function will work
google.maps.event.addListener(marker, 'click', function (event)
{
infowindowPhoto.open(map,marker);
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
latPosition = this.getPosition().lat();
longPosition = this.getPosition().lng();
});
I want when i drag the marker that this function work
google.maps.event.addListener(marker,'dragend', function (event)
{
infowindowPhoto.open(map,marker);
document.getElementById("latbox").value = this.getPosition().lat();
document.getElementById("lngbox").value = this.getPosition().lng();
newLocationLat = this.getPosition().lat();
newLocationLong = this.getPosition().lng();
});
So i can only show only my new position. Thanks for your help
/////////////////////////////////Update///////////////////////////////////
I have this code that show me the new latitude and longitude in an html input:
<div id="latlong">
<p>Latitude: <input size="20" type="text" id="latbox" name="lat" ></p>
<p>Longitude: <input size="20" type="text" id="lngbox" name="lng" ></p>

A few tips:
Avoid unnecessary code when you are having issues with a script. Break it down to the essential.
Always post the necessary code with your question (you have now updated it). Good point.
Avoid duplicating code at different places. Create functions for that.
I now understand you want to show the user location in 2 inputs. I thought you wanted to show it within the infowindow, which is what I did in the below code (but the main idea is the same).
A few notes:
Code within an event listener (click, dragend, etc.) is only executed when the event is fired.
You can use the setContent method of the infowindow when you want to update its content.
Here is the code:
var map;
var marker;
var infowindowPhoto = new google.maps.InfoWindow();
var latPosition;
var longPosition;
function initialize() {
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(10,10)
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
initializeMarker();
}
function initializeMarker() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
latPosition = position.coords.latitude;
longPosition = position.coords.longitude;
marker = new google.maps.Marker({
position: pos,
draggable: true,
animation: google.maps.Animation.DROP,
map: map
});
map.setCenter(pos);
updatePosition();
google.maps.event.addListener(marker, 'click', function (event) {
updatePosition();
});
google.maps.event.addListener(marker, 'dragend', function (event) {
updatePosition();
});
});
}
}
function updatePosition() {
latPosition = marker.getPosition().lat();
longPosition = marker.getPosition().lng();
contentString = '<div id="iwContent">Lat: <span id="latbox">' + latPosition + '</span><br />Lng: <span id="lngbox">' + longPosition + '</span></div>';
infowindowPhoto.setContent(contentString);
infowindowPhoto.open(map, marker);
}
initialize();
Here is the demo:
JSFiddle demo
Hope this helps! If you have questions, feel free to ask!

Related

Problems with geolocation

I want to make an application that shows your current position on a map with a marker. The code I've done seems to work but it doesn't display the marker. Can someone help me, please?
Here's my app.js:
var app = angular.module('starter', ['ionic', 'ngCordova']);
app.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
});
app.controller('MapController', function($scope, $cordovaGeolocation, $ionicLoading, $ionicPlatform) {
$ionicPlatform.ready(function() {
$ionicLoading.show({
template: '<ion-spinner icon="bubbles"></ion-spinner><br/>Acquiring location!'
});
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
$cordovaGeolocation.getCurrentPosition(posOptions).then(function(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: myLatlng,
zoom: 16,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
$scope.map = map;
$ionicLoading.hide();
}, function(err) {
$ionicLoading.hide();
console.log(err);
});
google.maps.event.addListener($scope.map, 'idle', function() {
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.map.LatLng(myLatlng)
icon:'http://i.imgur.com/fDUI8bZ.png'
});
var infoWindow = new google.maps.InfoWindow({
content: "Here I am!"
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(map, marker);
});
infowindow.open(map, marker);
});
})
});
You are using
var long = position.coords.longitude;
whereas long is a keyword in javascript. Check the link below.
https://www.w3schools.com/js/js_reserved.asp
Unless you are using ECMAScript 5/6 standard
Try to add Latitude and Longitude in following way to new google.map.LatLng(...)
var marker = new google.maps.Marker({
map: $scope.map,
position: new google.map.LatLng(lat, long)
icon:'http://i.imgur.com/fDUI8bZ.png'
});
Hope this will help to you
Spent a very hair-tearing hour or so trying to get the good old W3C geolocation example to work in my particular application. Didn't see this:
https://developers.google.com/web/updates/2016/04/geolocation-on-secure-contexts-only
If you are NOT using https you may (will?) get a silent, non-functioning outcome, both in Chrome and Firefox! As soon as I switched to https, it was fine.

Google Maps API - Activating the infowindow of a custom marker

I am trying to activate the infowindow for a custom marer, yielding a small description about the marker, I'm having some trouble at the moment, I have the custom marker working but I can't get the infowindow to show.
I tried calling the listener for the marker and storing it in a variable "customMarker", then calling another mouseover listener to activate the infowindow, but I'm having no luck, can anyone help me out?
var map;
//Creates a custom icon to be placed on the map
var goldStar = 'https://cdn2.iconfinder.com/data/icons/august/PNG/Star%20Gold.png';
function initialize() {
//Sets the zoom amount for the map, the higher the number, the closer the zoom amount
var mapOptions = {
zoom: 18
//center : myLatLng
};
//The map object itself
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
var contentString = 'This is a custom toolTip';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
// Tries to find user location using HTML 5
if(navigator.geolocation)
{
//sets the map to the position of the user using location
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
var customMarker = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng, map);
});
//This listener is not working
//google.maps.event.addListener(customMarker, 'mouseover', function() {
//infowindow.open(map,customMarker);
//});
}
function placeMarker(location, map)
{
var marker = new google.maps.Marker({
position: location,
icon: goldStar,
map: map,
title: "custom marker",
draggable:true
});
map.panTo(location);
}
The google.maps.event.addListener function does not return a marker. This won't work:
var customMarker = google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng, map);
});
Assign the event listener in your placeMarker function to the marker you create (also gives the advantage of maintaining function closure on the marker):
function placeMarker(location, map) {
var marker = new google.maps.Marker({
position: location,
icon: goldStar,
map: map,
title: "custom marker",
draggable: true
});
var contentString = 'This is a custom toolTip';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'mouseover', function() {
infowindow.open(map,marker);
});
map.panTo(location);
}
working fiddle

Make geocoding map zoom on scroll

I am looking at two different geocode examples I found and I am looking to get the best of both features. I have not had much experience with geocoding and I find the google docs hard to follow
This one does everything I want except scroll in when the user uses the mouse wheel. http://jsfiddle.net/Ep7Rr/
I would like this one if I could get the marker to move as the user drags the map like in the first one.http://jsfiddle.net/AjeTc/
I know there are different ways such as new GMap2 and new google.maps.Geocoder
The first one works with this code
<script>
function load() {
if (GBrowserIsCompatible()){
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var center = new GLatLng(54.18173, -6.35284);
map.setCenter(center, 15);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function(){
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function(){*/
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").innerHTML = center.lat().toFixed(5);
document.getElementById("lng").innerHTML = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").innerHTML = point.lat().toFixed(5);
document.getElementById("lng").innerHTML = point.lng().toFixed(5);
}); /*END GEvent.addListener(marker, "dragend", function() {*/
}); /*END GEvent.addListener(map, "moveend", function() {*/
} /*END if (GBrowserIsCompatible()){*/
} /*END function load*/
And the second uses this
<script type="text/javascript">
function showAddress() {
var map = new GMap2(document.getElementById("map"));
var address = document.getElementById('fullAddress').value;
return false;
} /*END function showAddress*/
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(54.18173, -6.35284);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Catch the event when the map is dragged.
Update the position of the marker by getting the map center
Geocode the position of the marker
google.maps.event.addListener(map, 'dragend', function() {
updateMarkerStatus('Drag ended');
marker.setPosition(map.getCenter());
geocodePosition(marker.getPosition());
});
like this : http://jsfiddle.net/ZYV9N/

Trouble clearing overlay when i reload a new set of markers in gmaps

I have a gmap and I only want to display markers in the viewable area. I have added a listener to get the bounds of the map and call gather the markers within the bounds. the problem is that when i bounds change, i want to clear the map and reload with the updated markers. currently the map will just continue to reload the markers on top of each other which makes the map extremely slow. I have tried:
google.maps.event.addListener(map, 'bounds_changed', function () {
clearOverlays();
loadMapFromCurrentBounds(map);
});
And that will not load any markers at all. I have also tried:
function loadMapFromCurrentBounds(map) {
clearOverlays();
And this will not load any markers either. Below is the code that will load all markers and functions as i want it to with the exception of clearing the old markers when the bounds change.
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, 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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
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() {}
Please help... I have been beating my head against the computer all night researching and trying to figure this out. Feel free to email and/or ask for any questions.
You cant remove all markers, but it is possible to setMap to null on every visible marker.
I am doing it like that
add markers array to map object
add clearAllMarkers function to map object
every marker is added to the map is also added to markers array
clearAllMarkers function is something like that:
for (var idx=0;idx<=map.markers.length;idx++){
map.markers[idx].setMap(null);
}
I belive you are adding separate markers object to you're markers array. You're markers array should be full of markers references!!!
var map = []; //elrado's code
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(40, -100),
zoom: 4,
mapTypeId: 'roadmap'
});
map.markers = [];//elrado's code (add narkers.array to map object)
google.maps.event.addListener(map, 'bounds_changed', function () {
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() {
if (map.markers) {
for (i in map.markers) { //Might be you'll need to use map.markers.length
markers[i].setMap(null);
}
map.markers = [];//reinit map.markers.array
}
}
function loadMapFromCurrentBounds(map) {
clearOverlays();
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, 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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
map.markers.push(marker);//elrado's code
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() {}
I have to warn you that this was written from the head (no test), but something like that should work. Basicly you are setting setMap(null) on separate markers not on objects you're showing on the map.
Below is the complete code solution to the problem.. Thanks for your help.
var map; //elrado's code
var markersArray = []; //elrados's code create array for markers
function load() {
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(33.553029,-112.054017),
zoom: 13,
mapTypeId: 'roadmap'
});
google.maps.event.addListener(map, 'tilesloaded', function () {
clearOverlays()
loadMapFromCurrentBounds(map);
});
}
function clearOverlays() { //clear overlays function
if (markersArray) {
for (i in markersArray) {
markersArray[i].setMap(null);
}
}
}
function loadMapFromCurrentBounds(map) {
var infoWindow = new google.maps.InfoWindow;
var bounds = map.getBounds(); // First, determine the map bounds
var swPoint = bounds.getSouthWest(); // Then the points
var nePoint = bounds.getNorthEast();
// Change this depending on the name of your PHP file
var searchUrl = 'Viewport_Search.php?west=' + swPoint.lat() + '&east=' + nePoint.lat() + '&south=' + swPoint.lng() + '&north=' + nePoint.lng();
downloadUrl(searchUrl, 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 point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var marker = new google.maps.Marker({
map: map,
position: point,
});
markersArray.push(marker); //eldorado's code Define the array to put markers in
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() {}

InfoWindow on Marker using MarkerClusterer

This is my html code. I've try anything to add an infowindow on the markers but it don't wanna work. My data is loading from the "Alle_Ortswahlen.page1.xml" file.
Do anyone have an idea how can I add infoWindow to each marker?
<script type="text/javascript">
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
</script>
Before the for cycle, make an empty infowindow object.
var infowindow = new google.maps.InfoWindow();
Than in the for cycle, after the marker, add an event listener, like this:
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
There is some closure magic happening when passing the callback argument to the addListener method. If you are not familiar with it, take a look at here:
Mozilla Dev Center: Working with Closures
So, your code should look something like this:
google.load('maps', '3', {
other_params: 'sensor=false'
});
google.setOnLoadCallback(initialize);
function initialize() {
var stack = [];
var center = new google.maps.LatLng(48.136, 11.586);
var options = {
'zoom': 5,
'center': center,
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), options);
var infowindow = new google.maps.InfoWindow();
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent("You might put some content here from your XML");
infowindow.open(map, marker);
}
})(marker, i));
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});
}
So what you need to do is add some code, inside your for-loop, associating an infowindow onclick event handler with each marker. I'm assuming you only want to have 1 infowindow showing at a time, i.e. you click on a marker, the infowindow appears with relevant content. If you then click on another marker, the first infowindow disappears, and a new one reappears attached to the other marker. Rather than having multiple infowindows all visible at the same time.
GDownloadUrl("Alle_Ortswahlen.page1.xml", function(doc) {
var xmlDoc = GXml.parse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("ROW");
// just create one infowindow without any content in it
var infowindow = new google.maps.InfoWindow({
content: ''
});
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("Field4"));
var lng = parseFloat(markers[i].getAttribute("Field6"));
var marker = new google.maps.Marker({
position : new google.maps.LatLng(lat, lng),
map: map,
title:"This is a marker"
});
// add an event listener for this marker
google.maps.event.addListener(marker , 'click', function() {
// assuming you have some content in a field called Field123
infowindow.setContent(markers[i].getAttribute("Field123"));
infowindow.open(map, this);
});
stack.push(marker);
}
var mc = new MarkerClusterer(map,stack);
});