I have a script that:
pulls results from a database in the form of an XML file
parses those results
creates a marker for each result and places it on a map (a single map for all markers)
at the same times, builds a clickable HTML list (sidebar) containing all those results.
When the user clicks on a place name in the sidebar, the info window from the corresponding marker on the map is automatically displayed. Of course the user can also click directly on a marker on the map, and the same info window is also displayed.
This code has been working fine for several years, but last week I noticed that its behavior was now bugged. When viewing some given results, the first click (either on the map or in the sidebar) works fine (the info window opens and displays the correct information), but the following clicks all show the same information from the first click, all in their respective info window. (To be clear: the information shown is the one from the very first click, not from the previous click.)
I've been trying to debug that for hours but I don't understand why it doesn't work anymore. As you can see in my code below, I tried adding a console.log in the google.maps.event.addListener function, to see what data is being worked with when the marker is clicked, but even there, I don't see anything wrong.
Here is my code (simplified to be more readable):
var side_bar_html = '\n';
var gmarkers = []; // array for created markers
var infoWindow;
var center_lat = <?php echo $position_lat; ?>;
var center_lng = <?php echo $position_lng; ?>;
function createMarker(point, name, html, place_id, map) {
var marker, markerOptions;
markerOptions = {
map: map,
position: point,
dataId: place_id,
icon : 'theme/marker.png',
shadow: 'theme/marker_shadow.png'
};
marker = new google.maps.Marker(markerOptions);
infoWindow = new google.maps.InfoWindow({content: html});
google.maps.event.addListener(marker, 'click', function() {
console.log(this, marker, html);
infoWindow.content = html;
infoWindow.open(map, this);
});
gmarkers.push(marker);
side_bar_html += '\n<li>' + name + '</li>';
return marker;
}
function showPlace(i) {
google.maps.event.trigger(gmarkers[i], 'click');
}
function loadEarth(opt, zoom) {
var map, point, mapCenter, mapOptions;
if (zoom === null) {zoom = 7;}
mapCenter = new google.maps.LatLng(center_lat, center_lng);
mapOptions = {
zoom: zoom,
center: mapCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
point = new google.maps.LatLng(parseFloat(center_lat), parseFloat(center_lng));
if (opt != 0) {
map.setMap(new google.maps.Marker(point));
}
}
// receiving results via XML
function go() {
var map, bounds;
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
bounds = new google.maps.LatLngBounds();
$.ajax({
url : 'url/to/data.xml',
type : 'GET',
dataType : 'xml',
success : function(xml) {
var markers, lat, lng, place_id, point, label, html, marker;
markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// extract data for each marker
lat = parseFloat(markers[i].getAttribute("lat"));
lng = parseFloat(markers[i].getAttribute("lng"));
place_id = parseFloat(markers[i].getAttribute("place_id"));
point = new google.maps.LatLng(lat,lng);
label = $(markers[i]).find('label').eq(0).text();
html = $(markers[i]).find('infowindow').eq(0).text();
// marker creation
marker = createMarker(point, label, html, place_id, map);
// extend visible zone to newly added marker
bounds.extend(point);
}
map.setCenter(new google.maps.LatLng(center_lat, center_lng), 7);
bounds.extend(point);
if (markers.length>0) {
document.getElementById("side_results").innerHTML = side_bar_html;
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
} else {
loadEarth();
}
} // end AJAX success
}); // end AJAX
} // end go()
if ($('#places_page').is('.empty')) {
loadEarth(0,8);
} else go();
Any help would be greatly appreciated.
Edit:
As requested, here's a sample of the XML received. In this case, the PHP variables at the start of the script would receive the following values:
$position_lat: 46.9479222
$position_lng: 7.4446085
<?xml version="1.0" encoding="UTF-8"?><markers>
<marker place_id="955" lat="46.950218" lng="7.442429">
<label><![CDATA[<em>Place 955</em><strong>3011 Bern</strong>]]></label>
<infowindow>
<![CDATA[<p><em>Place 955</em><br />Speichergasse 35<br />3011 <ins>Bern</ins></p>]]>
</infowindow>
</marker>
<marker place_id="985" lat="46.942032" lng="7.389993">
<label><![CDATA[<em>Place 985</em><strong>3018 Bern</strong>]]></label>
<infowindow>
<![CDATA[<p><em>Place 985</em><br />BrĂ¼nnenstrasse 106A<br />3018 <ins>Bern</ins></p>]]>
</infowindow>
</marker>
</markers>
The Google Maps API is included via this line:
<script src="http://maps.google.com/maps/api/js?v=3&sensor=true&language=fr&key=..."></script>
Edit 2:
Changing the API call to force it to use version 3.18 does fix the problem:
<script src="http://maps.google.com/maps/api/js?v=3.18&sensor=true&language=fr&key=..."></script>
Obviously this is a temporary fix, since v. 3.18 won't always be available. Now I need to understand what change in the 3.19 version made this bug appear. Any suggestion is still appreciated. :)
This undocumented usage:
infoWindow.content = html;
May be the issue. Should be:
infoWindow.setContent(html);
The .content property went away or is no longer supported issue
Related
I'm using a combination of Google Maps, GeoXML and MarkerClusterer to map historic texts to places. The user can choose the texts they want to map, and the page goes and gets the KML for those group of texts and displays it with MarkerClusterer.
Something is causing the page to recenter over India/China when new texts are selected (bottom left corner: http://lakes.jhadley.net/lit_file.htm.
Here is the primary function that deals with the map:
function loadMap(myLat, myLong, zoomLevel, generatedUrl) {
var mapOptions = {
center: new google.maps.LatLng(myLat, myLong),
zoom: zoomLevel,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var mcOptions = {gridSize: 80, maxZoom: 15};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
markerclusterer = new MarkerClusterer(map, [], mcOptions);
var myParser = new geoXML3.parser({
map: map,
singleInfoWindow:true,
suppressInfoWindows:true,
createMarker:function(placemark){
var point = placemark.latlng;
var info = "<pre" + placemark.name + "<br /><br />" + placemark.description + "</pre>";
var marker = new google.maps.Marker({position:point});
//Suppress the speachbubbles and have them appear in a text window instead
google.maps.event.addListener(marker, 'click', function() {
var text = placemark.description.replace(/ target="_blank"/ig, "");
showInContentWindow(text);
}); //Add listener
markerclusterer.addMarker(marker);
}
});
myParser.parse("http://lakes.jhadley.net/generateKml/"+generatedUrl);
function showInContentWindow(text) {
var sidediv = document.getElementById('kwic_window');
sidediv.innerHTML = text;
} //showInContentWindow
} //function loadMap
I can't personally see why the map centre is being repositioned over India/China when new texts are loaded. Can anyone tell me what I'm missing?
by default geoxml3 attempts to zoom to fit the data. If you don't want it to do that, set the "zoom" option to false. From the documentation:
zoom | boolean (true) | If true, the parser will automatically move the map to a best-fit of the geodata after parsing of a KML document completes.
That is where the "center" of the markers are:
http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_linktoB.html?filename=http://www.geocodezip.com/geoxml3_test/SO_20140312_1,4.kml
http://www.geocodezip.com/geoxml3_test/v3_geoxml3_kmltest_linktoB.html?filename=http://www.geocodezip.com/geoxml3_test/SO_20140312_1.kml
I'm working with google maps api and javascript which I am not much familiar with. Here's the code I use to draw markers on my map. I get Latitudes and Longitudes from my database:
var geocoder;
var map;
var jsonStr = '<?php echo json_encode($arajka) ?>';
var LatLong = JSON.parse(jsonStr);
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(50.000001, 20.000001),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = [];
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login}));
}
// trying to set some listener but it fails.
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
alert("ASDASDASD" + marker.ajdi);
});
}
So, this listener doesn't work, I don't know why. Well, I expect that it doesn't exactly know what marker is it about. When I tried to do it with a single one, like in tutorial, it worked properly. I don't know what to do when I have this array. Any suggestions please?
You have several mistakes in your code:
As #Hollister mentions, marker is an array, so you need to put the addListener call inside the loop;
You have to store the additional marker data into the marker, not into the marker array;
you have to use this in the listener, not marker.
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
var this_marker = new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login});
this_marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(this_marker);
// trying to set some listener but it fails.
google.maps.event.addListener(this_marker, 'click', function() {
map.setZoom(8);
map.setCenter(this.getPosition());
alert("ASDASDASD" + this.ajdi);
});
}
I have a set of jQuery UI tabs that each load project.php using ajax. Depending on the parameters passed to the script, a different Google map is displayed using the following JavaScript inside project.php:
var tab_index = $('#tabs').tabs('option', 'selected');
$('.site_map:visible').css('height','300px');
MapID = $('.site_map:visible').attr('id');
if (MapID !== 'map-new'){
var map_id = 'map-'+tab_index;
$('.site_map:visible').attr('id', map_id);
} else {
MapNewSite();
}
var latlng = new google.maps.LatLng(19,-70.4);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-" + tab_index), myOptions);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
placeMarker($('.site_details:visible .inpLat').val(), $('.site_details:visible .inpLng').val(), tab_index);
function MapNewSite(){
arrMaps[tab_index] = new google.maps.Map(document.getElementById("map-new"), myOptions);
placeMarker(19,-70.4,tab_index);
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
}
Each map loaded using parameters returned by a query of my database loads without any problems. However, in one last instance, I load project.php in a tab without any parameters so as to have a blank tab for users to manipulate. The signal that the map is not to be loaded using database coordinates is that the id of its div is "map-new".
The map generated in this tab loads, but then gives me the "a is null" error which usually means it couldn't find a div with the id specified to initialize the map. What is causing this error even after the map has loaded? How do I stop the error from occurring?
Here is the JavaScript in the parent page containing the tab site:
var arrMaps = {};
var arrInfoWindows = {};
var arrMarkers = {};
function placeMarker(lat, lng, tab_index){
map = arrMaps[tab_index];
var bounds = new google.maps.LatLngBounds();
var latlng = new google.maps.LatLng(
parseFloat(lat),
parseFloat(lng)
);
bounds.extend(latlng);
createMarker(latlng, tab_index);
map.fitBounds(bounds);
zoomChangeBoundsListener =
google.maps.event.addListener(map, 'bounds_changed', function(event) {
if (this.getZoom()){
this.setZoom(10);
}
google.maps.event.removeListener(zoomChangeBoundsListener);
});
}
function createMarker(latlng, tab_index) {
var html = 'Click here to move marker';
arrMarkers[tab_index] = new google.maps.Marker({
map: arrMaps[tab_index],
position: latlng
});
arrInfoWindows[tab_index] = new google.maps.InfoWindow();
google.maps.event.addListener(arrMarkers[tab_index], 'click', function() {
arrInfoWindows[tab_index].setContent(html);
arrInfoWindows[tab_index].open(arrMaps[tab_index], arrMarkers[tab_index]);
});
}
$(function() {
$( "#tabs" ).tabs({
ajaxOptions: {
error: function( xhr, status, index, anchor ) {
$( anchor.hash ).html(
"Couldn't load this tab. We'll try to fix this as soon as possible. " +
"If this wouldn't be a demo." );
}
},
cache: true
});
});
Take a look to http://www.pittss.lv/jquery/gomap/. Easy to use and very powerful. I myself use it.
It turns out I was accidentally initializing the map both inside the if and outside of it.
I've created a custom map with most things I want on it (custom icon and custom info bubble), however I can't find a solution to automatically open the markers info window on load, I've done alot of searching but can't seem to find anything the code I have so far is as follows, any help would be much appreciated:
function initialize() {
var myLatlng = new google.maps.LatLng(54.325109,-2.742226);
var myOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var countries = [
{
title:'Remedy',
lat:54.3210,
lon:-2.7438,
content:"<h2>Remedy</h2><p>address, <br />location, <br />postcode</p> <p><b>T:</b> 07595 153 835 <br /><b>E:</b> <a href='mailto:email'>email</a></p>"
}
];
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
icon: '/wp-content/themes/remedy/display_images/google_map_icon.png',
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
infowindow.open(map, marker);
}
Maybe it's not working because you just created the instance of the Map and didn't wait for the complete load of the map to open the InfoWindow.
Try something like this:
google.maps.event.addListenerOnce(map, 'tilesloaded', function(event) {
infowindow.open(map, marker);
});
According to the reference:
http://code.google.com/intl/en/apis/maps/documentation/javascript/reference.html#Map
tilesloaded - This event is fired when the visible tiles have finished loading.
Hmm, inforwindow does not refer to anything in your code, which is why it is not working.
Since you have one country in the list as of now you can do a quick test and intialize the infowindow variable with an actual info window, or better yet also since you have 1 item in the list, just define c to be outside the loop so you can access it and then open the popup passing it the map and the marker, something like this (assuming c has been defined outside the loop)
c.infowindow.open(map, c.marker);
var infowindow = new google.maps.InfoWindow({
content: "Test Route",
position: new google.maps.LatLng(38.8709866, -77.208055),
});
infowindow.open(map);
I have managed to get a google map on my site using Javascript api of google maps.. and it works great...
Can anyone tell me how i can add the Speech bubble and marker ... Pictured here... http://code.google.com/apis/maps/
Basically my site displays a simple map but its missing the marker for where office is and a speech bubble where i want to place the office address
Any help would be really appreciated.
Here is the code i have so far
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40.466997, -3.705482), 13);
}
A marker can be added using the GMarker class ; for instance, to add a point to a map, I would use something like this :
var point = new GPoint(45.779915302498935, 4.803814888000488);
var marker = new GMarker(point);
map.addOverlay(marker);
(Of course, you'll have to adapt the coordinates to the ones of your office, so it doesn't point to some point in France ^^ ; I suppose the ones you posted should do the trick ;-) )
And for an Information window, you can use the GMarker.openInfoWindowHhtml method, on your marker.
I guess something like this should do the trick :
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(40.466997, -3.705482), 13);
var point = new GPoint(-3.705482, 40.466997);
var marker = new GMarker(point); // Create the marker
map.addOverlay(marker); // And add it to the map
// And open some infowindow, with some HTML text in it
marker.openInfoWindowHtml(
'Hello, <strong>World!</strong>'
);
}
And the result looks like this :
(source: pascal-martin.fr)
Now, up to you to build from here ;-)
Here is some code that shows how to use an XML file to load multiple markers. Also this site is the best there is for Google Maps examples and tutorials
// A function to create the marker and set up the event window
function createMarker(point,name,html) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() {
marker.openInfoWindowHtml(html);
});
// save the info we need to use later for the side_bar
//gmarkers.push(marker);
// add a line to the side_bar html
//side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
return marker;
}
// This function picks up the click and opens the corresponding info window
function myclick(i) {
GEvent.trigger(gmarkers[i], "click");
}
$(document).ready(function(){
// When class .map-overlay-right is clicked map is loaded
$(".map-overlay-right").click(function () {
var map = new GMap2(document.getElementById('map-holder'));
$("#map-holder").fadeOut('slow', function(){
var gmarkers = [];
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
// Get XML file that contains multiple markers
$.get("http://www.foo.com/xml-feed-google-maps",{},function(xml) {
$('marker',xml).each(function(i) {
// Parse the XML Markers
html = $(this).text();
lat = $(this).attr("lat");
lng = $(this).attr("lng");
label = $(this).attr("label");
var point = new GLatLng(lat,lng);
var marker = createMarker(point,label,html);
map.addOverlay(marker);
});
});
});
$("#map-holder").fadeIn('slow');
var Asia = new GLatLng(19.394068, 90.000000);
map.setCenter(Asia, 4);
});
});