Streamlining code in the JavaScript Maps API

Since the Google Maps JS API v3 launched in 2009, we have added lots of new features. And we’ve also made occasional modifications to the API to minimize and simplify common code pathways for developers.

Today we want to announce two small, but useful, changes we have recently made. The first lessens the amount of code required to create a map. The second evolves the API towards a more standard pattern of using plain JavaScript objects.

The first change was introduced quietly a few versions ago, and made the Map Type an optional parameter (defaulting to the standard ROADMAP type) when instantiating a new map.

The second change is available in versions 3.16 of the API and above, and introduces a new way of creating a location: instead of google.maps.LatLng(37.5, -122.5), you can now simply pass in a plain JavaScript object like {lat: 37.5, lng: -122.5}.

Let’s take a look at how these changes affect the original code from our launch announcement above:

var myOptions = {
     zoom: 8,
     center: new google.maps.LatLng(-34.397, 150.644),
     mapTypeId: google.maps.MapTypeId.ROADMAP

   var myOptions = {
     zoom: 8,
     center: {lat: -34.397, lng: 150.644}

Note that since the order of the values no longer matters, the following is equally valid:
     center: {lng: 150.644, lat: -34.397}
The end result is less code needed to instantiate a basic map, less opportunity for confusion regarding coordinate ordering, and a more flexible way to create locations.

Note that google.maps.LatLng will continue to work, and there’s no need to modify any of your existing code. These new features are simply designed to help those getting started, and help you create more streamlined and readable code.

As always, we love to get feedback on how even minor changes like this affect your workflow. You can comment on this post or on our Google+ Page. And as always, you can get help on StackOverflow. Check out our support page for the right tags to use.

Posted by Josh Livni, Maps API Team