GMaps v3: infoWindow not closing - google-maps

I have a lot of markers on a single map, added in a for loop. I managed to make the infoWindows display as intended, but I have one problem - they won't close when the close button is clicked.
If I open a new one, the old one closes, which is good. I even managed to make it close when the user clicks anywhere else on the map.
I've been searching for a solution, but I haven't found anything. Ideally I would like to make the close button work, but I guess it'd be good enough if I could just hide it.
Here's some code:
Adding a marker:
function addMarker( map, lat, lon, title, center, image, link )
{
// create latlng object
var latLng = new google.maps.LatLng( parseFloat( lat ), parseFloat( lon ) );
// set image base URL
var imageBase = ajax_vars.home_url + '/images/map-markers/';
// set default image
if ( typeof( image ) == 'undefined' )
image = 'default';
// CREATE MAPS OBJECTS FOR THE MARKER
// main image
var icon = new google.maps.MarkerImage(
imageBase + image + '.png',
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
// shadow
var shadow = new google.maps.MarkerImage(
imageBase + image + '.shadow.png',
new google.maps.Size(32, 32),
new google.maps.Point(0,0),
new google.maps.Point(0, 32)
);
// shape
var shape = {
coord: [1, 1, 1, 32, 32, 32, 32 , 1],
type: 'poly'
};
// ADD MARKER
marker = new google.maps.Marker({
position: latLng,
title: title,
map: map,
shadow: shadow,
icon: icon,
shape: shape
});
// ADD INFOWINDOW TO MARKER
addInfoWindowToMarker( marker, title, link );
// CENTER MARKER IF REQUIRED
if ( center )
map.setCenter( latLng );
}
Adding info window:
function addInfoWindowToMarker( marker, title, link )
{
// WINDOW HTML CONTENT
// link html
if ( typeof( link ) == 'undefined' )
link = '';
else
link = "(<a href='" + link + "'>click to view</a>)";
// window html
var htmlContent = "<div class='infoWindow'>This is content for "
+ title
+ "<br/>"
+ link
+ "</div>"
// create object
infowindow = new google.maps.InfoWindow();
// CLICK EVENT LISTENER
google.maps.event.addListener( marker, 'click', function() {
infowindow.setContent( htmlContent ),
infowindow.open( map, marker ),
// trying to hide the button
// $( '.infoWindow' ).parent().parent().siblings().find( 'img' ).hide();
//$( '[src="http://maps.gstatic.com/mapfiles/mv/imgs8.png"]' ).hide();
});
// trying to close the winddow on click
google.maps.event.addListener( infowindow, 'closeclick', function(){
infowindow.open( null, null );
alert('closing');
});
}
The closeclick event is not even fired when I click the button.
The attempts to hide the button did nothing.
I get an error which I don't understand when I click on the marker :
Uncaught TypeError: Object # has no method 'M'
You can check out the map here.

I ran into something similar: the close button wasn't causing the infoWindow to close. In my case, the value of the map argument wasn't the correct element (it was a wrapper/container).
Once I passed the correct element, everything worked as expected.

Please refer the following example which i have used already.,
Step #1 : Include the Three script Files in header of your page.,like
(i). <script type="text/javascript" src="http://maps.google.com/maps?file=api&v=2&key=Your_API_KEY"></script>
(ii).<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
(iii).<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.2/jquery-ui.min.js"></script>
Step #2 : Scripts On Page
<script type="text/javascript">
//initialize the map window
jQuery(document).ready(function () {
load();
});
jQuery(window).unload(function () {
GUnload();
});
var map;
var geocoder;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function load() {
if (GBrowserIsCompatible()) {
geocoder = new GClientGeocoder();
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
//map.setCenter(new GLatLng(35.048629,-0.820663), 4);
searchLocations();
document.getElementById('directions-panel').innerHTML = '';
var url_new = ''+ benObj.TEMPLATE_DIR +'/print.html';
var print_icon_url_new = 'PrintLink';
jQuery('#print_icon').html(print_icon_url_new);
}
}
//Search Locations with address input
function searchLocations() {
var address = document.getElementById('addressInput').value;
// alert(address);
var address_new = jQuery("#addressInput_new").val();
if (address_new != "Enter City or Zip") {
jQuery("#loc1").html(address_new);
}
geocoder.getLatLng(address, function (latlng) {
//alert(latlng);
if (!latlng) {
alert(address + ' not found');
} else {
searchLocationsNear(latlng);
}
});
}
// Search Near By Location to place the Markers and Information windows
function searchLocationsNear(center) {
var radius = document.getElementById('radiusSelect').value;
var searchUrl = ''+ benObj.BASE_ROOT +'/mapmarker?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius + '&format=raw';
jQuery.get(searchUrl, function (data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');
map.clearOverlays();
var sidebar = document.getElementById('sidebar');
var sidebar_val = '';
//sidebar.innerHTML = 'Results Found';
jQuery("#sidebar").html(sidebar_val);
<!--jQuery("#loc_count").html(markers.length);-->
if (markers.length == 0) {
sidebar.innerHTML = 'No results found.';
map.setCenter(new GLatLng(35.048629, -0.820663), 4);
return;
}
var bounds = new GLatLngBounds();
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var phone_new = markers[i].getAttribute('phonenumber');
var distance = parseFloat(markers[i].getAttribute('distance'));
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
var markerchar = "b";
var marker = createMarker(point, name, address, phone_new);
map.addOverlay(marker);
// var location_count = jQuery('#loc_count').val();
jQuery('#loc_count').val(i + 1);
var sidebarEntry = createSidebarEntry(marker, name, address, distance, phone_new);
jQuery('#sidebar').append(sidebarEntry);
//sidebar.appendChild(sidebarEntry);
// ScrollPane.getContentPane().appendChild(sidebarEntry);
bounds.extend(point);
}
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
jQuery('#sidebar').jScrollPane();
//jQuery('#sidebar').reinitialise();
});
}
//To Create a Marker With Information Window
function createMarker(point, name, address, phone_new) {
var pinkIcon = new GIcon(G_DEFAULT_ICON);
pinkIcon.image = ""+ benObj.IMAGE_DIR +"addr-pin-1.png";
var markerOptions = {
icon: pinkIcon
};
var marker = new GMarker(point, markerOptions);
var event_calendar = "event_calendar";
var event_title = ""+ benObj.event_title +"";
var display = "block";
var e_dt_start = jQuery("#dtstart").val();
var e_dt_end = jQuery("#dtend").val();
var e_start_timestamp = (formatTimestring(e_dt_start));
var e_end_timestamp = (formatTimestring(e_dt_end));
var e_desc = jQuery("#edesc").val();
var StrippedString = e_desc.replace(/(<([^>]+)>)/ig, "");
var trimmed = StrippedString.replace(/^\s+|\s+$/g, '');
var html = '<b>' + name + '</b> <br/>' + address + '<br>contact: ' + phone_new + '<br><br>Add to Calendar<div class="summary" style="display:none;">' + event_title + ' - "' + name + '"</div><span class="dtstart date" title="' + e_dt_start + '" style="display:none;">8th Aug 2010</span><span class="dtend date" title="' + e_dt_end + '" style="display:none;">01:30am - 12:00pm</span><div class="event-desc" style="display:none;">' + trimmed + '</div><div class="event-locate" style="display:none;">' + name + ',' + address + '</div> | Remind Me<br><br>Get Direction From:<br><input type="hidden" id="start" value="' + address + '"><input type="text" id="end" value="" style="border: 1px solid #ECE6D5;"> <input type="button" value="GO" onclick="calcRoute();" style="border: 1px solid #ECE6D5;padding-left:5px;">';
GEvent.addListener(marker, 'click', function () {
marker.openInfoWindowHtml(html);
//jQuery(this).addtocal();
});
return marker;
}
// To Make Sidebar Entry If need
function createSidebarEntry(marker, name, address, distance, phone_new) {
var div = document.createElement('div');
var html = '<div class="locrow clearfix"><div class="left" style="width:240px;"><span class="count" id="loc_count">' + jQuery("#loc_count").val() + '</span><address><strong>' + name + '</strong>' + address + '</address><span class="mapdate"><span class="icon date"></span>'+ benObj.event_start_month_date +' – '+ benObj.event_end_month_date_year +'</span></div><div class="right" style="width:154px;"><ul><li><span class="icon phone"></span>' + phone_new + '</li><li><span class="icon time"></span>11 am – 7 pm</li><li><span class="icon car"></span>distance ' + distance.toFixed(1) + ' mi</li></ul></div></div>';
div.innerHTML = html;
div.style.cursor = 'pointer';
div.style.marginBottom = '5px';
GEvent.addDomListener(div, 'click', function () {
GEvent.trigger(marker, 'click');
});
GEvent.addDomListener(div, 'mouseover', function () {
div.style.backgroundColor = '#eee';
});
GEvent.addDomListener(div, 'mouseout', function () {
div.style.backgroundColor = '#fff';
});
return div;
}
// To make a Directions If need
function calcRoute() {
directionsDisplay = new google.maps.DirectionsRenderer();
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var url = "http://maps.google.co.in/maps?f=d&source=s_d&saddr=" + start + "&daddr=" + end + "&aq=0&vpsrc=0&hl=en&doflg=ptm&mra=ls&ie=UTF8&t=m&z=5&layer=c&pw=2";
var print_icon_url = 'PrintLink';
var request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var myOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(41.850033, -87.6500523)
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions-panel'));
directionsDisplay.setDirections(response);
jQuery('#print_icon').html(print_icon_url);
}
});
}
</script>
Step #3: To Create a XML For Markers and Information Windows
<?php
function mapMarker($center_lat,$center_lng,$radius)
{
$mysqli = $this->_getMySqlConnection();
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Search the rows in the markers table
$query = sprintf("SELECT phone,street_address_1, store_name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM locations HAVING distance < '%s' ORDER BY distance LIMIT 0 , 10",
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($center_lng),
$mysqli->real_escape_string($center_lat),
$mysqli->real_escape_string($radius));
$result = $mysqli->query($query);
header("Content-type: text/xml");
header('Access-Control-Allow-Origin: *');
$avoid_duplicate="";
// Iterate through the rows, adding XML nodes for each
while ($row = #$result->fetch_assoc())
{
if($avoid_duplicate!=$row['store_name'])
{
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("name", $row['store_name']);
$newnode->setAttribute("address", $row['street_address_1']);
$newnode->setAttribute("lat", $row['lat']);
$newnode->setAttribute("lng", $row['lng']);
$newnode->setAttribute("distance", $row['distance']);
$newnode->setAttribute("phonenumber", $row['phone']);
$avoid_duplicate=$row['store_name'];
}
}
$outXML=$dom->saveXML();
$result->close();
$mysqli->close();
return $outXML;
}
?>
Step #4: HTML Part
<div class="mapleft">
<div class="ScrollPane scroll-pane" id="sidebar" style="overflow: auto; height: 430px;"></div>
<div class="mapshadow"></div>
</div>
<input type="hidden" id="addressInput" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect" value="50" />
<input type="hidden" id="addressInput_temp" value="<?php echo $zip_code;?>" />
<input type="hidden" id="radiusSelect_temp" value="50" />
<input type="hidden" name="X_REQUESTED_WITH" value="XMLHttpRequest" />
<div class="mapright">
<div id="map" style="width: 475px; height: 450px"></div>
</div>
<div class="map-dir" id="directions-panel" style="float:right;width:488px;"></div>
<input type="hidden" id="loc_count" value="1" />
These are the things which will produce the great out comes. I think this may help you to resolve your problem.

At first sight, you are using commas instead of semicolons in your click handler:
google.maps.event.addListener( marker, 'click', function() {
infowindow.setContent( htmlContent ), ---> HERE
infowindow.open( map, marker ), ---------> AND HERE
Try replacing those for semicolons ; as that could probably be the error you are having.
UPDATE:
In your infowindow closeclick handler, replace your following line:
infowindow.open( null, null );
for this one:
infowindow.close();
As close() is the method normally used to close infowindows.

Related

Google Maps - Marker click event not firing

I am clearly doing something wrong, but danged if I know what it is. I have the following code where I put a map on a webpage, get the bounds, call back to my system and get locations within the system, and display markers on the map. I would like to display some data when the marker is clicked on, however, I am not getting the click event of a marker to fire. I am clearly missing something, but don't know what it is. Any ideas are appreciated. TIA.
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/ReportingWeb/NearbyCleanliness";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " +
(result[i].Address2 != null ? result[i].Address2 : "") +
" " + result[i].City + " " + result[i].Province + " " +
result[i].PostalCode + " " + result[i].Country;
var marker = new google.maps.Marker({
position: geocodeAddress(geocoder, map, address),
map: map,
title: address,
content: address
});
marker.addListener('click', function () {
console.log("clicked");
alert("hi");
});
}
});
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
geocodeAddress() is not returning a position, so your marker code is placed incorrectly.
The marker click listener should be set along with the marker-creation code inside geocodeAddress().
You were creating markers in inside geocodeAddress but setting the onclick outside of it, where they weren't working.
map.setZoom(12);
var Latitude = position.coords.latitude;
var Longitude = position.coords.longitude;
map.setCenter({ lat: Latitude, lng: Longitude });
var bounds = map.getBounds();
var url = "/api/ReportingWeb/NearbyCleanliness";
var lowerLeft = bounds.getSouthWest();
var upperRight = bounds.getNorthEast();
var lat0 = lowerLeft.lat();
var lng0 = lowerLeft.lng();
var lat1 = upperRight.lat();
var lng1 = upperRight.lng();
var geocoder = new google.maps.Geocoder();
var data = { LowerLeftLat: lat0, LowerLeftLng: lng0, UpperRightLat: lat1, UpperRightLng: lng1 };
$.get(url, data, function (result) {
for (var i = 0; i < result.length; i++) {
var address = result[i].Address1 + " " +
(result[i].Address2 != null ? result[i].Address2 : "") +
" " + result[i].City + " " + result[i].Province + " " +
result[i].PostalCode + " " + result[i].Country;
//-------need not create markers here------------------
geocodeAddress(geocoder, map, address);
}
});
//-------place marker onclicks inside the function------------------
function geocodeAddress(geocoder, resultsMap, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
resultsMap.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: resultsMap,
position: results[0].geometry.location,
title: address,
content: address
});
marker.addListener('click', function () {
console.log("clicked");
alert("hi");
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}

Google Maps V3 - Trigger an event listener for either a UI event or an MVC state change event

I have two listeners, one for user clicks and one for "insert_at". I want to implement a self-completion polygon. So initially the user will click to draw a polygon. When the user is drawing the polygon, I don't want to trigger the "insert_at" listener. After the polygon is completed, I want the "insert_at" listener to be triggered. How do I do that? My code snippets below:
var poly;
var map;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {lat: 3.165236, lng: 101.654315} //choose an appropriate center for the map
});
poly = new google.maps.Polygon({
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3,
editable: true
});
poly.setMap(map);
map.addListener('click', addLatLng);
google.maps.event.addListener(poly.getPath(), 'insert_at', function(index, obj) {
var path = poly.getPath();
//Only insert if it's not the last coordinate
if ($("#polygon-coordinates").find("div.nested-fields ").eq(index).length > 0) {
$("#polygon-coordinates").find("div.nested-fields").eq(index - 1).after('<div class="nested-fields row"></br><div class="col-xs-6"></br><label>Latitude</label></br><input class="form-control" id=""area[polygon_coordinates_attributes][' + index + '][latitude]" name="area[polygon_coordinates_attributes][' + index + '][latitude]" value="' + path.b[index].lat() + '"></div>' +
'<div class="col-xs-6"></br><label>Longitude</label></br><input class="form-control" name="area[polygon_coordinates_attributes][' + index + '][longitude]" name="area[polygon_coordinates_attributes][' + index + '][longitude]" value="' + path.b[index].lng() + '"></div></br></div>');
addMarker(path.b[index], index);
}
});
google.maps.event.addListener(poly.getPath(), 'set_at', function(index, obj) {
var path = poly.getPath();
var lat = "area[polygon_coordinates_attributes][" + index + "][latitude]";
var lng = "area[polygon_coordinates_attributes][" + index + "][longitude]";
$("input[name='" + lat + "']").val(path.b[index].lat());
$("input[name='" + lng + "']").val(path.b[index].lng());
//delete existing marker here
deleteMarker(index);
debugger
addMarker(path.b[index], index);
});
}
function isNotDupMarker(path, index) {
//check if the coordinates are duplicated
if (markers[index - 1] !== undefined && path[index].lat() !== markers[index - 1].position.lat()) {
return true;
} else {
return false;
}
}
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
markers.push(marker);
}
function deleteMarker(index) {
markers[index].setMap(null);
}
// Handles click events on a map, and adds a new point to the Polyline.
function addLatLng(event) {
var path = poly.getPath();
// Because path is an MVCArray, we can simply append a new coordinate
// and it will automatically appear.
var index = path.push(event.latLng);
var i = index - 1
addMarker(event.latLng, index);
$("#polygon-coordinates").append('<div class="nested-fields row"></br><div class="col-xs-6"></br><label>Latitude</label></br><input class="form-control" id=""area[polygon_coordinates_attributes][' + i + '][latitude]" name="area[polygon_coordinates_attributes][' + i + '][latitude]" value="' + path.getAt(index - 1).lat() + '"></div>' +
'<div class="col-xs-6"></br><label>Longitude</label></br><input class="form-control" name="area[polygon_coordinates_attributes][' + i + '][longitude]" name="area[polygon_coordinates_attributes][' + i + '][longitude]" value="' + path.getAt(index - 1).lng() + '"></div></br></div>');
}

Google maps marker infowindow a href not rendering as a link

I have successfully managed to make xml from mysql and present markers on a map (wo-hoo).
The script includes a infowindow with some basic data. I want to have the URL open en new window with the external URL.
The URL and the a href tag shows beautifully - and that's the issue - I want to be able to click on it :)
Could someone please help me with the code to do this? Bear in mind I have used a week to get the markers from the db. I'm in no position to rebuild the code (I hope).
This is the output I get
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(37.4419, 10.0),
zoom: 3
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP or XML file
downloadUrl('mapxml.php', function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var name = markerElem.getAttribute('name');
var country = markerElem.getAttribute('country');
var url = markerElem.getAttribute('url');
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = name
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('url');
text.textContent = "<a href='" + url + "'>" + name + "</a>";
infowincontent.appendChild(text);
var marker = new google.maps.Marker({
map: map,
position: point,
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
});
});
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
Unless you're working with custom html elements, the following
var text = document.createElement('url');
text.textContent = "<a href='" + url + "'>" + name + "</a>";
won't work. You should try instead
var text = document.createElement('a');
text.href=url;
text.textContent = name;

Google Maps Auto Zoom and Auto Center

Originally we entered the zoom and coordinates. Now we would like it to auto zoom and auto center. Tried bounds.extend() with map.fitBounds(); map.panToBounds(); and can't seem to get it to zoom and center properly. Original code below. Any help greatly appreciated.
<script>
var mapfunction = function() {
$this = $("#map_canvas");
$zoom_level = ($this.data("gmap-zoom") || 5);
$data_lat = ($this.data("gmap-lat") || 29.895883);
$data_lng = ($this.data("gmap-lng") || -80.650635);
$xml_src = ($this.data("gmap-src") || "xml/gmap/pins.xml");
nvisionhstyleMap = new google.maps.StyledMapType(nightvision_highlight_style, {
name: "Nightvision"
});
function xmlLoadMap() {
var centerLatLng = new google.maps.LatLng($data_lat, $data_lng),
mapOptions = {
zoom: $zoom_level,
center: centerLatLng,
//disableDefaultUI: true,
//mapTypeId : google.maps.MapTypeId.ROADMAP
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'nightvision_highlight_style'
]
}
},
bounds = new google.maps.LatLngBounds(),
infowindow = new google.maps.InfoWindow(),
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.mapTypes.set('nightvision_highlight_style', nvisionhstyleMap);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
// map.setMapTypeId('metro_style');
$.get($xml_src, function(data) {
// create the Bounds object
var bounds = new google.maps.LatLngBounds();
$(data).find("marker").each(function(){
var eachMarker = jQuery(this),
// grab the address from XML
theAddress = eachMarker.find("address").text(),
mygc = new google.maps.Geocoder(theAddress);
mygc.geocode({'address' : theAddress}, function(results, status) {
var mLat = results[0].geometry.location.lat(),
Long = results[0].geometry.location.lng(),
marker = new google.maps.Marker({
position : new google.maps.LatLng(mLat, Long),
map : map,
icon : ('img/' + eachMarker.find("icons").text() + '.png'),
scrollwheel : false,
streetViewControl : true,
title : eachMarker.find("name").text()
}),
link = "link";
google.maps.event.addListener(marker, 'click', function() {// click
// Setting the content of the InfoWindow
var contentString = '<div id="info-map" style="width:300px; height:85px; padding:0px;"><div>' + '<div style="display:inline-block; width:86px; verticle-align:top; float:left;"><img src=' + eachMarker.find("image").text() + ' class="thumbnail" style="width:80%; verticle-align:top;" /></div>' + '<div style="display:inline-block; width:200px; float:left;"><h4>' + eachMarker.find("name").text() + '</h4><b>' + eachMarker.find("address").text() + '</b><br/>' + '<p><i class="fa fa-fw fa-map-marker"></i>More Info</p>' + '</div></div></div>';
infowindow.setContent(contentString);
infowindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infowindow.close()
})
});
});// end geocode
});// end find marker loop
}); // end get data
} // end xmlLoadMap
// grey
xmlLoadMap();
};
// end pagefunction
// run pagefunction on load
$(window).unbind('gMapsLoaded');
$(window).bind('gMapsLoaded', mapfunction);
window.loadGoogleMaps();
Here is what we tried with `bound.extend'. It changes from the default value but centers it 0,0 instead of to the markers.
<script>
var mapfunction = function() {
$this = $("#map_canvas");
$zoom_level = ($this.data("gmap-zoom") || 5);
$data_lat = ($this.data("gmap-lat") || 29.895883);
$data_lng = ($this.data("gmap-lng") || -80.650635);
$xml_src = ($this.data("gmap-src") || "xml/gmap/pins.xml");
nvisionhstyleMap = new google.maps.StyledMapType(nightvision_highlight_style, {
name: "Nightvision"
});
function xmlLoadMap() {
var centerLatLng = new google.maps.LatLng($data_lat, $data_lng),
mapOptions = {
zoom: $zoom_level,
center: centerLatLng,
//disableDefaultUI: true,
//mapTypeId : google.maps.MapTypeId.ROADMAP
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.TERRAIN, 'nightvision_highlight_style'
]
}
},
bounds = new google.maps.LatLngBounds(),
infowindow = new google.maps.InfoWindow(),
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.mapTypes.set('nightvision_highlight_style', nvisionhstyleMap);
map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
// map.setMapTypeId('metro_style');
$.get($xml_src, function(data) {
// create the Bounds object
var bounds = new google.maps.LatLngBounds();
$(data).find("marker").each(function(){
var eachMarker = jQuery(this),
// grab the address from XML
theAddress = eachMarker.find("address").text(),
mygc = new google.maps.Geocoder(theAddress);
mygc.geocode({'address' : theAddress}, function(results, status) {
var mLat = results[0].geometry.location.lat(),
Long = results[0].geometry.location.lng(),
marker = new google.maps.Marker({
position : new google.maps.LatLng(mLat, Long),
map : map,
icon : ('img/' + eachMarker.find("icons").text() + '.png'),
scrollwheel : false,
streetViewControl : true,
title : eachMarker.find("name").text()
}),
link = "link";
bounds.extend(new google.maps.LatLng(mLat, Long));
google.maps.event.addListener(marker, 'click', function() {// click
// Setting the content of the InfoWindow
var contentString = '<div id="info-map" style="width:300px; height:85px; padding:0px;"><div>' + '<div style="display:inline-block; width:86px; verticle-align:top; float:left;"><img src=' + eachMarker.find("image").text() + ' class="thumbnail" style="width:80%; verticle-align:top;" /></div>' + '<div style="display:inline-block; width:200px; float:left;"><h4>' + eachMarker.find("name").text() + '</h4><b>' + eachMarker.find("address").text() + '</b><br/>' + '<p><i class="fa fa-fw fa-map-marker"></i>More Info</p>' + '</div></div></div>';
infowindow.setContent(contentString);
infowindow.open(map, marker);
google.maps.event.addListener(map, 'click', function() {
infowindow.close()
})
});
});// end geocode
});// end find marker loop
}); // end get data
map.fitBounds(bounds);
map.panToBounds(bounds);
} // end xmlLoadMap
// grey
xmlLoadMap();
};
// end pagefunction
// run pagefunction on load
$(window).unbind('gMapsLoaded');
$(window).bind('gMapsLoaded', mapfunction);
window.loadGoogleMaps();
Got it! map.fitBounds() needs to be called before Geocode end. Added address_count++ to geocode and called map.fitBounds() on last marker.
if(address_count == $(data).find("marker").length) {
map.fitBounds(bounds);
map.panToBounds(bounds);
}
});// end geocode
});// end find marker loop
}); // end get data
} // end xmlLoadMap
xmlLoadMap();
};

Google Maps Api V3 Zoom links in infowindow not working

I am building a store locator using php sql and javascript. I've done this tutorial https://developers.google.com/maps/articles/phpsqlsearch_v3 and got it working. I am trying to implement zoom in/out links on the infoWindows, for when the user clicks a marker. Its not working, in FireFox I am getting no errors in the console. In Chrome I am getting Uncaught TypeError: Object # has no method 'setCenter'
Ive been searching the forums but have been unable to find a solution. Sorry I dont have a version online to look at, working locally. Below is the script I am using.
var map = null;
var markers = [];
var infoWindow;
var locationSelect;
//On page load Create a google map in #map
//Set default cordinates & Map style to roadmap
function load() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(43.907787,-79.359741),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
infoWindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
locationSelect = document.getElementById("locationSelect");
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
if (markerNum != "none") {
google.maps.event.trigger(markers[markerNum], 'click');
}
};
}
//Search for LAT/LNG of a place using its address using Google Maps Geocoder
function searchLocations() {
var address = document.getElementById("addressInput").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
searchLocationsNear(results[0].geometry.location);
} else {
alert(address + ' not found');
}
});
}
//Clears Prve location, in info box
function clearLocations() {
infoWindow.close();
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers.length = 0;
locationSelect.innerHTML = "";
var option = document.createElement("option");
option.value = "none";
option.innerHTML = "See all results:";
locationSelect.appendChild(option);
}
//Look for locations near by and loop through all data getting lat & lng of each marker
function searchLocationsNear(center) {
clearLocations();
var radius = document.getElementById('radiusSelect').value;
var searchUrl = 'http://localhost:8888/starward/wp-content/themes/starward/map_request.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
downloadUrl(searchUrl, function(data) {
var xml = parseXml(data);
var markerNodes = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markerNodes.length; i++) {
var name = markerNodes[i].getAttribute("name");
var address = markerNodes[i].getAttribute("address");
var distance = parseFloat(markerNodes[i].getAttribute("distance"));
var zoom = 18;
var latlng = new google.maps.LatLng(
parseFloat(markerNodes[i].getAttribute("lat")),
parseFloat(markerNodes[i].getAttribute("lng")));
createOption(name, distance, i);
createMarker(latlng, name, address,zoom);
bounds.extend(latlng);
}
map.fitBounds(bounds);
map.setZoom(11);
// map.setCenter(center);
locationSelect.style.visibility = "visible";
locationSelect.onchange = function() {
var markerNum = locationSelect.options[locationSelect.selectedIndex].value;
google.maps.event.trigger(markers[markerNum], 'click');
};
});
}
//Creates marker on the map
//Adds event for user when they click address info pops up
function createMarker(latlng, name, address, zoom) {
//var html = "<b>" + name + "</b> <br/>" + address
// add the zoom links
var html = "<b>" + name + "</b> <br/>" + address
html += '<br>Zoom To';
html += ' [+]';
html += ' [-]';
var marker = new google.maps.Marker({
position: latlng,
map: map
});
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
marker.MyZoom = zoom;
markers.push(marker);
}
function createOption(name, distance, num) {
var option = document.createElement("option");
option.value = num;
option.innerHTML = name + "(" + distance.toFixed(1) + ")";
locationSelect.appendChild(option);
}
//Look up XML sheet to get data
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
callback(request.responseText, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function parseXml(str) {
if (window.ActiveXObject) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.loadXML(str);
return doc;
} else if (window.DOMParser) {
return (new DOMParser).parseFromString(str, 'text/xml');
}
}
It works for me in both IE and Firefox. Although to me the behavior makes more sense if I set the center for the "ZoomTo" link as well:
html += '<br>Zoom To';