Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Conditional Running of Function (for Google Maps)

4:39 am on Jan 22, 2010 (gmt 0)

Junior Member

10+ Year Member

joined:May 12, 2007
posts: 91
votes: 0

I am setting up a store locator and have everything working great using the sample code provided by Google here: [code.google.com...]

I have a map centering/zoom issue. The problem I run into is when my search returns 0 results.

Within function load() is a statement that centers my map on the USA (zoomed out):
map.setCenter(new GLatLng(40, -100), 3);

So we are off to a great start, except that the very next line calls showMap() which re-centers the map and zoom to fit the incoming data points (in this case, there are none). This command ends up centering over the Pacific Ocean and zooming out to a "world view" level. (Note, when I do pass in marker locations in the XML file, everything zooms appropriately...no problem there.)

I am sure that there is some easy conditional statemene that could go somewhere to check if there ae any incoming "markers" and if not, skip the whole re-centering and zooming command. PELASE HELP!

My problem lies with the last line of each of the following two functions. Here is the code (slightly simplified from the Google original):

function load() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById('map'));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.setCenter(new GLatLng(40, -100), 3);

function showMap() {
var searchUrl = 'map_points.xml';
GDownloadUrl(searchUrl, function(data) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName('marker');

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 distance = parseFloat(markers[i].getAttribute('distance'));
var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),parseFloat(markers[i].getAttribute('lng')));

var marker = createMarker(point, name, address, distance);
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

4:59 am on Jan 22, 2010 (gmt 0)

Senior Member

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member

joined:Nov 28, 2004
votes: 0

(mis read question, will try again tomorrow when I'm more alert)
10:54 am on Jan 22, 2010 (gmt 0)

Preferred Member

10+ Year Member

joined:Aug 18, 2008
votes: 0

var markers = xml.documentElement.getElementsByTagName('marker');

getElementsByTagName returns an array-like object which has a length property, so check the length. Add this immediately after the above line:
if (!markers.length) { return; }
2:23 pm on Jan 22, 2010 (gmt 0)

Junior Member

10+ Year Member

joined:May 12, 2007
votes: 0

Perfect. That works great. THANK YOU!