Googlemaps - removing previous marker - javascript

After some advice on how to clear markers on googlemaps, I have a map which I would like to have only one marker showing (basically the last marker clicked). I would like the user to be able to change thier mind and click multiple times, but not have confusing map of previous clicks etc.
I have tried the map.clearOverlay(); function, but it seems to permantly clear the whole map.
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("googlemap"));
map.setCenter(new GLatLng(50.401515,-4.866943), 8);
GEvent.addListener(map,"click", function(overlay,latlng) {
if (latlng) {
var myHtml = "" + latlng ;
split=myHtml.indexOf(",");
x=Math.round(myHtml.slice(1,split)*1000000)/1000000;
y=Math.round(myHtml.slice(split+1,myHtml.length-1)*1000000)/1000000;
document.collector.latitude.value=x;
document.collector.longitude.value=y;
lat="<br />Latitude: " + x;
lon="<br />Longitude: " + y;
latlon=""+lat+lon;
//map.openInfoWindow(latlng, latlon);
map.clearOverlay();
map.addOverlay(new GMarker(latlng));
}
});
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
}
}

Untested, but should do what you want - note that the setLatLng method of GMarker was introduced in API version 2.88:
function initialize() {
if (GBrowserIsCompatible()) {
var marker;
function showNewMarker(latlng) {
marker = new GMarker(latlng);
map.addOverlay(marker);
showMarker = updateExistingMarker;
}
function updateExistingMarker(latlng) {
marker.setLatLng(latlng);
}
var showMarker = showNewMarker;
var map = new GMap2(document.getElementById("googlemap"));
map.setCenter(new GLatLng(50.401515,-4.866943), 8);
GEvent.addListener(map,"click", function(overlay,latlng) {
if (latlng) {
var myHtml = "" + latlng ;
split=myHtml.indexOf(",");
x=Math.round(myHtml.slice(1,split)*1000000)/1000000;
y=Math.round(myHtml.slice(split+1,myHtml.length-1)*1000000)/1000000;
document.collector.latitude.value=x;
document.collector.longitude.value=y;
lat="<br />Latitude: " + x;
lon="<br />Longitude: " + y;
latlon=""+lat+lon;
//map.openInfoWindow(latlng, latlon);
map.clearOverlay();
showMarker(latlng);
}
});
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
}
}
It works by using a variable, showMarker, containing a reference to a function. This starts out pointing to a function, showNewMarker, which creates a marker, adds it to the map, and then changes showMarker to point to the function updateExistingMarker, which simply uses setLatLng to move the marker to a new position. This means that, on subsequent clicks, the existing marker will be moved to the location of the click.

Related

Add info for multiple markers from dynamic content

I have an array like this deviceId = [005305230001JIZZZZ, 085835360001NBGJZZ, 085835360002NBGJZZ].
The info window should show the deviceId and be displayed based on which marker is clicked. I started looking at JavaScript only a few days back and can't understand how the functions work and dont have the time right now to learn becauseI have to get this done. I saw a few implementations on this, but I think they have done the adding multiple markers differently using functions, I think. I couldn't understand it so I used for loop.
The latArray and lngArray have something like this [12.1456,12.5256,11.566] and [72.145,72.4557,75.23535]
I cant figure out how to add info windows for corresponding markers.
This is the code for map:
function initMap() {
var bounds = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0],lngArray[0]));
map.setZoom(18);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(latArray[i],lngArray[i]),
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
//bounds.extend(marker.getPosition());
console.log(latArray);
console.log(lngArray);
}
//map.fitBounds(bounds);
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
How to show info window of corresponding markers.
This is content for marker:
contentString = '<div id = "content>'
+'<p style = "color:#000000">DeviceID<p>' +
'<p>'+ deviceId[i] + '<br></p>' //deviceId is the array with content
+ '</div>'
I read something about closures but didn't understand. Please help
Edit: I just tried this. I'm getting js?callback=initMap:34 InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object
What i tried:
var markerArray=[];
for(i=0;i<latArray.length;i++)
{
markerArray.push("new google.maps.LatLng("+ latArray[i]+","+lngArray[i]+")");
console.log(markerArray[i]);
}
console.log(markerArray[0]);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: markerArray[i],
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
var infoWindow = new google.maps.InfoWindow({
content: contentString[i]
});
marker.addListener('click', function(marker,contentString) {
infoWindow.open(map, marker);
});
}
So I will not bother you with the explanation how closures work (as you are saying your not interested in it now), I just supply you the solution:
// Your arrays with geo informations
var latArray = [-25.363, -26.263, -25.163];
var lngArray = [131.044, 131.144, 132.044];
// Your array with device information
var deviceIdArray = ["AAA", "BBB", "CCC"];
// Just create map according to the first geo info
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latArray[0], lng: lngArray[0]},
zoom: 6
});
// Loop throuhg all geo info
latArray.forEach(function(lat, i) {
// For each one create info window
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content>'
+ '<p style="color:#000000">DeviceID<p>'
+ '<p>'+ deviceIdArray[i] + '</p>'
+'</div>'
});
// For each one create marker
var marker = new google.maps.Marker({
map: map,
position: {lat: latArray[i], lng: lngArray[i]}
});
// Click on the currently created marker will show the right info window
marker.addListener("click", function() {
infoWindow.open(map, marker);
});
});
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
Take a look at my function with map. It takes json object with some data from PHP and 'translate' it into array and then adds content to multiple markers (it is not dynamic in real time - you have to reload page). In addition it has a search box (which opens certain info window). If you don't understand do not hestitate to ask :).
//check if document is fully loaded, seetting a container for ajax call results
$(document).ready(function() {
var tablica = [];
// ajax call for action preparing set of names, descriptions, coords and slugs needed to render deatiled markers on map
$.ajax({
url: 'map/json_prepare',
dataType: 'json',
success: function(response) {
var obj = JSON && JSON.parse(response) || $.parseJSON(response);
obj.forEach(function(item, index, array)
{
tablica.push(item);
});
//call a function rendering a map itself
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.06561980, lng: 19.946850},
zoom: 12
});
////////////////////////////////////////////////////////////////////////////////////////////////////
// LOOP ADDING MARKERS FROM DB WITH PROPER INFO WINDOWS (DESCRIPTION AND LINKS)
// Add a markers reference
var markers = [];
$.each(tablica, function( key, value ) {
//markers
var myLatLng = {lat: value[1], lng: value[2]};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: value[0],
clickable: true,
animation: google.maps.Animation.DROP,
adress: value[5]
});
//infowindows
marker.info = new google.maps.InfoWindow ({
content: '<h1>'+ value[0] + '</h1>' + '<br>' + '<br>' + value[3] + '<br>' + value[5] +'<br>' + '<br>' + '' + 'Details' + '<br/>' +
'' + 'Take part in' + '<br>'
});
//eventlistener - after click infowindow opens
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
//event listener - after dblclick zoom on certain event is set
google.maps.event.addListener(marker, 'dblclick', function() {
map.setZoom(18);
map.setCenter(marker.getPosition());
});
markers.push(marker);
});
// End of loop adding markers from db.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///additional event listener - rightclick to get back default zoom
google.maps.event.addListener(map, 'rightclick', function() {
map.setZoom(12);
map.setCenter(map.getPosition());
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CENTRING MAP AS ALL OF MARKERS IS VISIBLE//
//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < tablica.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(tablica[i][1], tablica[i][2]),
map: map
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
}
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
///SEARCH_BOX////////
///Here comes part of script adding search box
// Create the search box and link it to the UI element.
// Anchor search box and search button to the map.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
var button = document.getElementById('submitSearch');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(button);
//replacing polish characters on order to search without necessity typing them
function cleanUpSpecialChars(str)
{
str = str.replace(/[Ą]/g,"A");
str = str.replace(/[ą]/g,"a");
str = str.replace(/[Ę]/g,"E");
str = str.replace(/[ę]/g,"e");
str = str.replace(/[Ć]/g,"C");
str = str.replace(/[ć]/g,"c");
str = str.replace(/[Ł]/g,"L");
str = str.replace(/[ł]/g,"l");
str = str.replace(/[Ń]/g,"N");
str = str.replace(/[ń]/g,"n");
str = str.replace(/[Ó]/g,"O");
str = str.replace(/[ó]/g,"o");
str = str.replace(/[Ś]/g,"S");
str = str.replace(/[ś]/g,"s");
str = str.replace(/[Ź]/g,"Z");
str = str.replace(/[ź]/g,"z");
str = str.replace(/[Ż]/g,"Z");
str = str.replace(/[ż]/g,"z");
return str;
}
//Function, that search in array of markers, one which fits the key word written in searchbox.
$('#submitSearch').click(function() {
//Catching searched word and preparing its value for search process
var toSearch = $(input).val().trim();
toSearch = cleanUpSpecialChars(toSearch);
toSearch = toSearch.toLowerCase();
console.log('Szukana fraza -> ' + toSearch);
var results = [];
if (toSearch.length >=3) {
// Iterate through the array
$.each(markers, function (i, marker) {
//preparing certain elemnts of marker objects for search process
markers[i].title = cleanUpSpecialChars(markers[i].title);
markers[i].adress = cleanUpSpecialChars(markers[i].adress);
markers[i].title = markers[i].title.toLowerCase();
markers[i].adress = markers[i].adress.toLowerCase();
if (markers[i].title.indexOf(toSearch) > -1 || markers[i].adress.indexOf(toSearch) > -1) {
results.push(markers[i]);
}
});
if (results.length < 1) {
console.log ('nic');
$('#message2').slideDown(500, function () {
setTimeout(function () {
$('#message2').slideUp(500);
}, 5000);
});
}
// Close all the infoWindows, before rendering Search results.
markers.forEach(function (marker) {
marker.info.close(map, marker);
});
//Opens infWindows for multiple markers found and set bounds so that all markers found are visible
results.forEach(function (result) {
result.info.open(map, result);
bounds.extend(result.position);
});
map.fitBounds(bounds);
}
else{
//what if user has typed less than three characters in searchbox -> render flash mess.
$("#message").slideDown(500, function(){
setTimeout(function(){
$("#message").slideUp(500);
},5000);
});
}
});
//Enabling key Enter for triggering a search action.
$(input).keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#submitSearch').click();//Trigger search button click event
}
});
},
//////////////////////////////////////////////////////////////////////////////////////////
//obsługa błędu, jeśli nie zostanie wyświetlona mapa
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(ajaxOptions);
alert('Map is broken. Please try again later.')
}
});
});
It will not qork here because it doesn't contain data from php.

automatically update marker google maps v3

Good afternoon, I created a map that fills markers with coordinates directly from my mysql database, the map is being generated correctly and markers work when I load the page. Every minute I get new coordinates in the bank and want to update the map with a time interval. For this I used the setInterval that calls the initialization function of the markers, however, are not creating new markers on the map, is always displaying the same, they only update when I give f5 on the page, ie if reloading the page works, but with no interval. He even winked on the map when the time set by the interval, but not updated.
My code:
<script src="js/markerclusterer.js"></script>
<script src="js/jquery-1.5.2.min.js"></script>
<script src="js/jquery.maskedinput-1.3.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
<?php
if($attmap_form > 0) {
echo 'myTimer = window.setInterval(refreshMapa,"'.$attmap_form.'");';
}
?>
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-25.4848801,-49.2918938),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
locations = [];
<?php
require('conecta.php');
$sql_lista = ("SELECT MONITLATITUDE,MONITLONGITUDE,MONITDATA,MONITHORA,MONITRAIO,MONITPROVEDOR,MONITVELOCIDADE FROM MONITORAMENTO where MONITHORA BETWEEN '$hora1_form' AND '$hora2_form' AND MONITDATA BETWEEN '$data1_form' AND '$data2_form' AND EQUIPIMEI = $imei");
$query_lista = mysql_query($sql_lista);
$achados_lista = mysql_num_rows($query_lista);
while ($achados_lista = mysql_fetch_array($query_lista)) {
$lat = $achados_lista['MONITLATITUDE'];
$lon = $achados_lista['MONITLONGITUDE'];
$Data = $achados_lista['MONITDATA'];
$hora = $achados_lista['MONITHORA'];
$raio = $achados_lista['MONITRAIO'];
$provedor = $achados_lista['MONITPROVEDOR'];
$velocidade = $achados_lista['MONITVELOCIDADE'];
echo 'locations.push ( {Data:"'.$Data.'", latlng: new google.maps.LatLng('.$lat.', '.$lon.'), hora:"'.$hora.'", raio:"'.$raio.'",provedor:"'.$provedor.'",velocidade:"'.$velocidade.'"} );';
}
?>
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
var markers = [];
for(var i=0;i < locations.length;i++ ) {
var marker = new google.maps.Marker({
position: locations[i].latlng,
map:map,
title:locations[i].hora
});
markers.push(marker);
bounds.extend(locations[i].latlng);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(
'<strong>Data: ' + locations[i].Data + '<br>Hora: ' + locations[i].hora + '<br></strong>Velocidade aproximada: ' + locations[i].velocidade + ' K/H<br>Raio aproximado de: ' + locations[i].raio + ' metros <br>Provedor: ' + locations[i].provedor + '<br>Latitude: ' + locations[i].latlng
);
infowindow.open(map, marker);
}
})(marker, i));
}
markerClusterer = new MarkerClusterer(map, markers, {
maxZoom: 16,
gridSize: 60
});
map.fitBounds(bounds);
}
arrancaMapa();
function arrancaMapa() {
google.maps.event.addDomListener(window, 'load', initialize);
}
function refreshMapa() {
initialize();
arrancaMapa();
}
function clearMarkers() {
setAllMap(null);
}
function stopTimer() {
$("#campoAttMap").val("0");
clearInterval(myTimer);
}
</script>
You shouldn't have to call initialize more than once. You should implement a different logic, for example get the newest marker that is not in the map and add it via
var marker = new google.maps.Marker({
position: locations[i].latlng,
map:map,
title:locations[i].hora
});
markers.push(marker);
bounds.extend(locations[i].latlng);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(
'<strong>Data: ' + locations[i].Data + '<br>Hora: ' + locations[i].hora + '<br></strong>Velocidade aproximada: ' + locations[i].velocidade + ' K/H<br>Raio aproximado de: ' + locations[i].raio + ' metros <br>Provedor: ' + locations[i].provedor + '<br>Latitude: ' + locations[i].latlng
);
infowindow.open(map, marker);
}
})(marker, i));
UPDATE:
I will add take the following approach. I don't like mixing PHP and Javascript together, I prefer using JSON and AJAX request.
Update your functions to look like this:
var map;
var markers = [];
setInterval(refreshMapa, 3000);
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-25.4848801,-49.2918938),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = [];
$.get("getmarkers.php", function(response){
for(var i = 0; i < response.markers.length; i++) {
var marker = response.markers[i];
var myMarker = {
Data: marker.Data,
latlng: new google.maps.LatLng(marker.lat, marker.lon),
hora: marker.hora,
raio: marker.raio,
provedor: marker.provedor,
velocidade: marker.velocidade
};
locations.push(myMarker);
addMapMarker(myMarker);
}
},'json');
markerClusterer = new MarkerClusterer(map, markers, {
maxZoom: 16,
gridSize: 60
});
map.fitBounds(bounds);
}
function refreshMapa() {
// make sure this one only returns markers that are new and not in the map
$.get("getnewmarkers.php", function(){
for(var i = 0; i < response.markers.length; i++) {
var marker = response.markers[i];
var myMarker = {
Data: marker.Data,
latlng: new google.maps.LatLng(marker.lat, marker.lon),
hora: marker.hora,
raio: marker.raio,
provedor: marker.provedor,
velocidade: marker.velocidade
};
locations.push(myMarker);
addMapMarker(myMarker);
}, 'json');
}
function addMapMarker(myMarker) {
var marker = new google.maps.Marker({
position: myMarker.latlng,
map:map,
title:myMarker.hora
});
markers.push(marker);
bounds.extend(myMarker.latlng);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<strong>Data: ' + myMarker.Data + '<br>Hora: ' + myMarker.hora + '<br></strong>Velocidade aproximada: ' + myMarker.velocidade + ' K/H<br>Raio aproximado de: ' + myMarker.raio + ' metros <br>Provedor: ' + myMarker.provedor + '<br>Latitude: ' + myMarker.latlng);
infowindow.open(map, marker);
}
})(marker, i));
}
PS: I'm not sure if the implementation of the addMapMarker is correct I just assumed you had it right in the first place, you should check the documentation and make sure it is correct.
Yeah so the thing is, PHP is a server-side language that only gets executed when the page loads. I'm not sure exactly how you would expect your JS to update the markers, as there are no get/post anywhere. If you want to get data from the server, you have to contact the server.
This loop
while ($achados_lista = mysql_fetch_array($query_lista)) {
$lat = $achados_lista['MONITLATITUDE'];
$lon = $achados_lista['MONITLONGITUDE'];
$Data = $achados_lista['MONITDATA'];
$hora = $achados_lista['MONITHORA'];
$raio = $achados_lista['MONITRAIO'];
$provedor = $achados_lista['MONITPROVEDOR'];
$velocidade = $achados_lista['MONITVELOCIDADE'];
echo 'locations.push ( {Data:"'.$Data.'", latlng: new google.maps.LatLng('.$lat.', '.$lon.'), hora:"'.$hora.'", raio:"'.$raio.'",provedor:"'.$provedor.'",velocidade:"'.$velocidade.'"} );';
}
Only gets executed ONCE. The value of locations doesn't change.
You should read up on jQuery ajax requests. Make an HTTP request to a PHP file that returns the locations as JSON (just echo the JS array) and use the result to update the markers.
Reason:
There is no update function (or code blocks) to get updated or newly added DB info in your code. Also, you will not read and add new db info to your map data because your PHP code is only called once at initialization-time.
Using PHP codes, you will not do it because of the PHP features. PHP will only work on back-end service sides.
Suggestion:
1. You need client-side updates to access service side updates and receive them.
2. You need to add the updated or newly added db data to your Marker (map) array on client sides.
For this,
1. Add client side update features in AJAX or others to update the info to JSON objects.
2. Call the AJAX block (retrieving block or function to read in JSON object array and add them to map marker arrays).
3. Update null pointer of Map Markers to the new Map array.
Sorry for not creating a working code set based on your codes. It will take a fairly long while.

Stop InfoWindow on Google Maps showing on load

Hi I am trying to integrate gmap with my website.But by default the infowindow is opened.I want to open the infowindow after clicking on the markers.How to close the infowindow on page load?
function initialize() {
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(22.4642600, 70.0690540), 6);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.addMapType(G_SATELLITE_3D_MAP);
for (var i = 0; i < newpoints.length; i++) {
var point = new GPoint(newpoints[i][1], newpoints[i][0]);
var popuphtml = newpoints[i][4];
var post_url = newpoints[i][5];
var addr = newpoints[i][6];
var marker = createMarker(point, newpoints[i][2], popuphtml, post_url, addr);
map.addOverlay(marker);
}
}
}
function createMarker(point, icon, popuphtml, post_url, addr) {
var popuphtml = '<div id="popup">' + popuphtml + '<div><a href=' + post_url + '>Link</a></div></div>';
var marker = new GMarker(point);
marker.openInfoWindowHtml(popuphtml);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(popuphtml);
});
return marker;
}
Remove this line
marker.openInfoWindowHtml(popuphtml);
so it becomes
function createMarker(point, icon, popuphtml, post_url, addr) {
var popuphtml = '<div id="popup">' + popuphtml + '<div><a href=' + post_url + '>Link</a></div></div>';
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function () {
marker.openInfoWindowHtml(popuphtml);
});
return marker;
}
you were calling the openInfoWindowHtml method immediately ... now its only called when the click event of the marker occurs
Note
You are using Google Maps V2 ... this is the message from google related to V2
Note: The Google Maps Javascript API Version 2 has been officially deprecated as of May 19, 2010. The V2 API will continue to work as per our deprecation policy, but we encourage you to migrate your code to version 3 of the Maps Javascript API.
remove the marker.openInfoWindowHtml(popuphtml); after var marker = new GMarker(point);

To get the position of draggable markers

I am using draggable markers in google maps. I have to get the position of markers after dragging because i have to store the new position of marker
The code is
var m = new GMarker(point,{draggable: true});
m.entry_id = id;
m.isMarker = true;
app.entries[id].marker = m;
Here is my example that will display the new location of the marker in and info-window at the new location after the marker has been dragged:
//assuming u have lat and long as latitude and longitude of the initial position
var location = new GLatLng(lat,long);
var marker = new GMarker(location, {draggable: true});
GEvent.addListener(marker, "dragstart", function() {
map.closeInfoWindow();
});
GEvent.addListener(marker, "dragend", function() {
var latlng = marker.getLatLng();
marker.openInfoWindowHtml("New Lat : " + latlng.lat() + ", New Long : " + atlng.lng() );
});
Am assuming you are using API version 2, the solution is a bit different for Version 3, but just a matter of change in the calling conventions sort of.

Infowindow in Googlemaps wont fill

I've got the following problem with Googlemaps.
I've created a createMarker function which returns a marker which I publish with addOverlay(). This works perfect, the marker get shown but the only problem is the click event voor the marker, I want a infowindow which is populated with the 'I want this text to be published' text, instead it gets populated with a var called html which I set in the beginning of my code (var html = 'test';), I received earlier a message with 'html is not defined', this is why is set the html var. Every infowindow has the text 'test' in it. I've tried using updateInfoWindow() but that doesn't work, anyone familiar with this problem? I can supply you with the full source but I think the createMarker function should be enough.
function GM_load() {
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.enableScrollWheelZoom();
map.setMapType(G_HYBRID_MAP);
geocoder = new GClientGeocoder();
GM_showItems();
}
function GM_showItems() {
GDownloadUrl("modules/Googlemaps/ajax/getItems.php", function(data, responseCode) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//start
var itemid = markers[i].getAttribute('id');
var title = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var city = markers[i].getAttribute('city');
var x = 0;
if (geocoder) {
geocoder.getLatLng(address + ' ' + city,
function(point) {
if (!point) {
alert(address + ' ' + city + " not found");
} else {
x = x+1;
Marker = createMarker(point, x);
map.addOverlay(Marker);
}
}
);
}
}
});
}
function createMarker(latlng, number) {
var marker = new GMarker(latlng);
marker.value = number;
GEvent.addListener(marker,"click", function() {
map.openInfoWindowHtml(latlng,'i want this text to be published');
});
return marker;
}
Solved.
I overwrite var html. not perfect but it works.

Categories

Resources