Google Maps InfoBubble windows neither closing nor recentering map - google-maps-api-3

I have a successful working GM prototype using InfoBubble here.
I need the map to recenter when I open each new InfoBubble window.
The map recenters on closing each InfoBubble because I call [line 238 etc]:
google.maps.event.addListener(infoBubble, "closeclick", function ()
Secondly, why doesn't the Los Angeles (United States West Coast, LA) InfoBubble also close the most recent InfoBubble window open as all the others do, please?
Thanks so much in advance for any suggestions; I know it must be simple - but have spent hours and hours and searched S/O too!
javascript:
$(document).ready(function () { initialize(); });
var myLatlng = new google.maps.LatLng(51.30, 0.7);
function initialize() {
google.maps.Map.prototype.setCenterWithOffset = function(LatLng, offsetX, offsetY) {
var map = this;
var ov = new google.maps.OverlayView();
ov.onAdd = function() {
var proj = this.getProjection();
var aPoint = proj.fromLatLngToContainerPixel(LatLng);
aPoint.x = aPoint.x+offsetX;
aPoint.y = aPoint.y+offsetY;
map.setCenter(proj.fromContainerPixelToLatLng(aPoint));
};
ov.draw = function() {};
ov.setMap(this);
};
var centerMap = new google.maps.LatLng(51.30, 0.7);
var mapOptions = {
zoom: 2,
disableDefaultUI: true,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false,
scaleControl: false,
draggable: false,
center: centerMap,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setCenterWithOffset(myLatlng, 50, 225);
setMarkers(map, sites);
google.maps.event.addListener(infoBubble, "closeclick", function () {
map.setCenterWithOffset(myLatlng, 50, 225);
});
google.maps.event.addListener(infoBubbleLA, "closeclick", function () {
map.setCenterWithOffset(myLatlng, 50, 225);
});
};
var infoBubble = new InfoBubble({
maxWidth: 400,
});
var infoBubbleLA = new InfoBubble({
maxWidth: 400,
});
// locationstrings start
var losangeles1 = 'losangeles1';
var losangeles2 = 'losangeles2';
var losangeles3 = 'losangeles3';
var losangeles4 = 'losangeles4';
var losangelescontentString ='losangelescontentString';
var portonovocontentstring ='Porto Novo';
var shackletoncontentstring = 'Shackleton';
var florencecontentstring = 'Florence';
var buenosairescontentstring = 'Buenos Aires';
var jodhpurcontentstring = 'Jodhpur';
var mtsinaicontentstring = 'Mt Sainai';
var neworleanscontentstring = 'New Orleans';
var pariscontentstring='Paris';
// locationstrings end
infoBubbleLA.addTab('Electronic Cataloguing Initiative', losangeles1);
infoBubbleLA.addTab('Getty Leadership Institute at Claremont Graduate University', losangeles2);
infoBubbleLA.addTab('Tab 3', losangeles3);
infoBubbleLA.addTab('Preserve L.A.', losangeles4);
var sites = [
// 'Title', lat, long, contentstring
['Los Angeles', 34.054082,-118.24261, losangelescontentString],
['Porto Novo', 6.501411,2.604275, portonovocontentstring],
['Shackleton', -77.550000, 166.150000, shackletoncontentstring],
['Florence', 43.773046,11.255901, florencecontentstring],
['Buenos Aires', -34.578528,-58.526273, buenosairescontentstring],
['Jodhpur', 27.199507,73.73826, jodhpurcontentstring],
['Mt Sinai', 28.555972,33.975048, mtsinaicontentstring],
['New Orleans', 29.984676,-90.063171, neworleanscontentstring],
['Paris', 48.821799,2.404933, pariscontentstring]
];
var iconBase = 'http://gettylabs.org/visit/FoundationMap/images/';
function setMarkers(map, markers) {
for (var i = 0; i < markers.length; i++) {
var sites = markers[i];
var siteLatLng = new google.maps.LatLng(sites[1], sites[2]);
var marker = new google.maps.Marker({
icon: iconBase + 'bullet.png',
title: sites[0],
position: siteLatLng,
html: sites[3],
map: map
});
google.maps.event.addListener(marker, "click", function () {
map.setCenterWithOffset(myLatlng, 50, 25);
if (this.html == losangelescontentString) {
infoBubbleLA.setContent(this.html);
infoBubbleLA.open(map,this);
} else {
infoBubble.setContent(this.html);
infoBubble.open(map,this);
}
});
};
};

You have 2 different InfoBubbles in you code infoBubbleLA and infoBubble. Opening one won't close the the other.
var infoBubble = new InfoBubble({
maxWidth: 400,
});
var infoBubbleLA = new InfoBubble({
maxWidth: 400,
});
This should do that:
google.maps.event.addListener(marker, "click", function () {
map.setCenterWithOffset(myLatlng, 50, 25);
if (this.html == losangelescontentString) {
infoBubbleLA.setContent(this.html);
infoBubbleLA.open(map,this);
infoBubble.close();
} else {
infoBubble.setContent(this.html);
infoBubble.open(map,this);
infoBubbleLA.close();
}
});
working fiddle

Related

I could not delete polygon when marker is click

I am trying to delete a polygon when my marker is being clicked,but i could not get how to make this work that the polygon will be deleted.I appreciate someone will help me to make this work.
This my demo in jsfiddle.
Demo
here is my code it's not working.
var map;
var count = 0;
var polycolor = '#ED1B24';
var polyarray = [];
var marker;
var markers = [];
var path = new google.maps.MVCArray;
function initialize() {
var initial = new google.maps.LatLng(53.199246241276875, -105.76864242553711);
var mapOptions = {
zoom: 16,
center: initial,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
mapTypeControl: false
};
poly.setPaths(new google.maps.MVCArray([path]));
map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
google.maps.event.addListener(map, 'click', function (e) {
addMarker(e);
addPolygon(e);
});
}
var deletepolygon = function (pt) {
i = 0;
var thepath = poly.getPath();
thepath.forEach(function (ltlng) {
i++;
if ((ltlng.lat() + "," + ltlng.lng()) == pt) {
path.removeAt(i);
}
});
}

More Efficient Way to Add Markers to Google Maps v3

I am building this JS programmatically. Each marker is being represented by separate variables like marker_0,marker_1, etc... This works but is there a way to generate the markers & info windows in a more efficient/elegant way?
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
//**************************************************************
//Add 1st marker
//**************************************************************
var contentString_0 ='<strong>Club name: Fort Wayne Time Corners</strong>';
var infowindow_0 = new google.maps.InfoWindow({
content: contentString_0
});
var image_0 = '/js/markers/marker1.png';
var Latlng_0 = new google.maps.LatLng(41.057814980291,-85.329851919709);
var marker_0 = new google.maps.Marker({
position: Latlng_0,
title:"0",
icon: image_0});
marker_0.setMap(map);
google.maps.event.addListener(marker_0, 'click', function() {
infowindow_0.open(map,marker_0);
});
//**************************************************************
//Add 2nd marker
//**************************************************************
var contentString_1='<strong>Club name: Roanoke</strong>';
var infowindow_1 = new google.maps.InfoWindow({
content: contentString_1
});
var image_1 = '/js/markers/marker2.png';
var Latlng_1 = new google.maps.LatLng(41.17805990,-85.4436640);
var marker_1 = new google.maps.Marker({
position: Latlng_1,
title:"1",
icon: image_1});
marker_1.setMap(map);
google.maps.event.addListener(marker_1, 'click', function() {
infowindow_1.open(map,marker_1);
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
</script>
Yes, you can do this easily:
Create an array of data that describes each marker.
Write a function that adds a single marker based on the description in one entry of that array.
Call that function for each entry in that array.
So the only part you have to generate dynamically is that array of data; all of the actual marker code is shared for all markers.
Like this:
var map;
var places = [
{
lat: 41.057814980291,
lng: -85.329851919709,
image: 'marker1',
title: '0',
club: 'Fort Wayne Time Corners'
},
{
lat: 41.17805990,
lng: -85.4436640,
image: 'marker2',
title: '1',
club: 'Roanoke'
}
];
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map-canvas"),
mapOptions
);
for( var i = 0; i < places.length; i++ ) {
addPlace( places[i] );
}
function addPlace( place ) {
var content = '<strong>Club name: ' + place.club + '</strong>';
var infowindow = new google.maps.InfoWindow({
content: content
});
var image = '/js/markers/' + place.image + '.png';
var latlng = new google.maps.LatLng( place.lat, place.lng );
var marker = new google.maps.Marker({
position: latlng,
title: place.title,
icon: image
});
marker.setMap( map );
google.maps.event.addListener( marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;

Google maps v3 geocode multiple custom markers by address or latlng

I need to plot multiple custom map markers using MapsV3 api either by an address or lat/lon. I put together the following code which works ok for lon/lat, but if the data contains an address the geocoder returns nothing. Any ideas on how to fix this.
$(document).ready(function () { initialize(); });
function initialize() {
var centerMap = new google.maps.LatLng(-27.0,133.0);
var options = {
panControl: false,
zoomControl: true,
scaleControl: false,
mapTypeControl: false,
streetViewControl: false,
zoom: 3,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var data = [
{
'title':'F C Building Construction ...',
'address':'',
'zindex':20,
'lat':'-33.797847',
'lon':'151.259928',
'marker_number':1,
'marker_html':' html content...',
'image': {
url:'//localhost/assets/images/markers/marker_1.png',
size: new google.maps.Size(24, 29),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(10, 29)
}
}];
setMarkers(map, data);
var infowindow = new google.maps.InfoWindow();
}
function showMapPin(i) { }
function setMarkers(map,data) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
setMarker(map, data[i], bounds);
}
map.fitBounds(bounds);
}
function setMarker(map, m, bounds) {
if(m["address"]!="") {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": m["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var siteLatLng = results[0].geometry.location;
}
});
} else {
var siteLatLng = new google.maps.LatLng(m["lat"], m["lon"]);
}
if(siteLatLng) {
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
//shadow: shadow,
icon: m["image"],
title: m["title"],
zIndex: m["zindex"],
html: m["marker_html"]
});
bounds.extend(siteLatLng);
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} // if latlng
}//]]>
After looking back over the code I realized that the variable siteLatLng is within geocode function scope so it never gets passed and it can't be returned. Setting the marker within this function works.

Google Map Marker not being replaced

please excuse a noob at this. When a user clicks on a map, it should place a marker and open an info window - as per this example: http://www.geocodezip.com/v3_example_click2add_infowindow.html
The code below almost works correctly, except that the mark is not replaced - a new one is added. Any ideas really, really gratefully received. Thank you.
<script>
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var marker , i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
This is a scope issue. You are always delcaring marker in the placeMarker function so if( marker ) will always be false. Move the variable declaration out of that function:
<script>
var marker;
var map = null;
var markersArray = [];
function initialize() {
var latlng = new google.maps.LatLng(0.0000, 0.0000);
var settings = {
zoom: 2,
mapTypeControl:true,
center: latlng,
panControl:true,
zoomControl:true,
streetViewControl:false,
overviewMapControl:false,
rotateControl:true,
scaleControl: true,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
},
mapTypeId: google.maps.MapTypeId.ROADMAP,
backgroundColor: 'white'
};
map = new google.maps.Map(document.getElementById('map'), settings);
function placeMarker(location) {
var i ;
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
icon:'http://www.desperatesailors.com/templates/Live/media/mapicons/info.png',
map: map
});
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() +
'<br>Longitude: ' + location.lng() +
'<br>Only the first four decimal places needed'
});
infowindow.open(map,marker);
}
}
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
window.onload = initialize;
</script>
Your placeMarker function creates a new (empty) marker variable in the local scope.
function placeMarker(location) {
var marker , i ;
if ( marker ) {
It will always create a new marker. Change it to:
var marker = null;
function placeMarker(location) {
if ( marker ) {

update infowindows when calling again a xml file

Good morning.
I have the next code which put some markers in a map from a xml file, every 5 seconds I call again the xml file and I update the position of the markers, but the problem is that the infowindows are not updated. Does anyone knows how to update them=
Here you have the code:
//<![CDATA[
var side_bar_html = "";
var gmarkers = [];
var map = null;
var markerclusterer = null;
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
map.setZoom(map.getZoom()+2);
}
function initialize() {
// create the map
var myOptions = {
zoom: 12,
center: new google.maps.LatLng(37.169619,-3.756981),
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),
myOptions);
}
function getMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" "+speed+" km/h <br/> "+timestamp;
var marker = createMarker(point,alias+" "+imei,html,estado,alias, speed, timestamp, altitude, angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,60)
});
setInterval(function updateMarkers() {
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
downloadUrl("vehiculos.asp", function(doc) {
var xmlDoc = xmlParse(doc);
var markers = xmlDoc.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
// obtain the attribues of each marker
var lat = parseFloat(markers[i].getAttribute("lat"));
var lng = parseFloat(markers[i].getAttribute("lng"));
var point = new google.maps.LatLng(lat,lng);
var imei = markers[i].getAttribute("imei");
var alias = markers[i].getAttribute("alias");
var speed= markers[i].getAttribute("speed");
var timestamp= markers[i].getAttribute("timestamp");
var estado= markers[i].getAttribute("estado");
var conectado= markers[i].getAttribute("conectado");
var altitude= markers[i].getAttribute("altitude");
var angle= markers[i].getAttribute("angle");
var html="<b>"+alias+" a "+speed+" km/h <br/> "+timestamp;
var newLatLng = gmarkers[i].setPosition(point,alias+" "+imei,html,estado,alias,speed,timestamp,altitude,angle);
}
markerCluster = new MarkerClusterer(map, gmarkers);
});
}, 5000);
//finish updateMarkers
function createMarker(latlng, imei, html, estado, alias, speed, timestamp, altitude, angle) {
if(estado == 1)
image = '/artworks/icons/truck_green3.png';
else
image = '/artworks/icons/truck_red.png';
var textoLabel= alias+" speed: "+ speed+" km/h";
var contentString = html;
var newLatLng = new MarkerWithLabel({
position: latlng,
icon: image,
// map: map,
draggable: true,
flat: true,
labelContent: textoLabel,
labelAnchor: new google.maps.Point(40, 0),
labelClass: "labels", // the CSS class for the label
labelStyle: {
opacity: 0.50
},
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
});
gmarkers.push(newLatLng);
// side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + imei +'<\/a><br>';
}
You are not assigning the event handler in the setInterval function, so no infowindows.
Add this code to the setInterval() after creating the marker
google.maps.event.addListener(newLatLng, 'click', function() {
infowindow.setContent(timestamp + alias);
infowindow.open(map,newLatLng);
This may result in a closure problem as you are in a loop. So you can do something like the solutions in this Passing values in for loop to event listeners- Javascript.

Resources