Google Maps API v3, brief overview

May 23rd, 2010 by Alex Leave a reply »

First of all, i gotta say to all those who still use Google Maps v2 or even v1, switch to v3 immediately! 😉
I wanna show you why now.. first of all, this is how you can load the Google Maps API:

<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>

See something new? Exactly, no API keys or whatever else. Google Maps is totally open and simple to use now, i will show how to use the main features and what to start from.

First, let’s make the map object global by declaring it outside our initializing functions, and let’s start declaring our init function:

var map;
 
function loadMap() {
  // let's just input New York City latitude/longitude
  var loc = new google.maps.LatLng(40.47, 73.58);
  var myOptions = {
    zoom: 7,
    center: loc,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map"), myOptions);
}

Here we define a Location object and define basic options (zoom level 7, center map on our location and set the map type to Road Map), and lastly init our map with new keyword.

Now let’s add a marker with our latitude and longitude:

var marker = new google.maps.Marker({
  position: loc, 
  map: map, 
  title:"New York City"
});

t, let’s add a function which will centrify our map to our location

google.maps.event.addListener(map, 'zoom_changed', function() {
  setTimeout(centrify, 1500);
});
 
function centrify() {
  var loc = new google.maps.LatLng(40.47, 73.58);
  map.setCenter(loc);
}

Oh and don’t forget to add

<div id='map'></div>

in your html.

The overall javascript for our example will look like this:

var map;
function loadMap() {
    var loc = new google.maps.LatLng(40.47, 73.58);
    var myOptions = {
	zoom: 7,
	center: loc,
	mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map"), myOptions);
 
    google.maps.event.addListener(map, 'zoom_changed', function() {
        setTimeout(centrify, 1500);
    });
 
    var marker = new google.maps.Marker({
        position: loc, 
        map: map, 
        title:"New York City"
    });
 
}
 
function centrify() {
  var loc = new google.maps.LatLng(40.47, 73.58);
  map.setCenter(loc);
}

Run the loadMap within the <body> tag on load.

<body onload='loadMap()'>
...
</body>

This page can be found by searching for:

settimeout google mapsmap setcenter V3



1 comment

  1. Patrick says:

    Clean, precise, easy to read. Just what I was looking for, at the right moment. Thanks.