27.10.2014 Views

Google Maps API 3

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 8 ■ CREATING POLYLINES AND POLYGONS<br />

var map = new google.maps.Map(document.getElementById('map'), options);<br />

};<br />

})();<br />

There’s nothing new in this code at all. All it does is create a blank <strong>Google</strong> map that is centered<br />

somewhere on the West Coast of the United States.<br />

Preparing the Coordinates<br />

As you now know, a polyline consists of several coordinates (points on the map). In this case, you’re<br />

going to create a very small polyline with just two points. To get started, you need to find out what these<br />

coordinates are.<br />

Fortunately, I have already found out the correct coordinates (see Table 8-1).<br />

Table 8-1. The Coordinates for San Francisco and Los Angeles<br />

City Latitude Longitude<br />

San Francisco 37.7671 -122.4206<br />

Los Angeles 34.0485 -118.2568<br />

To use these coordinates, you need to convert them to objects of the type google.maps.LatLng and<br />

add them to an array. Create an array called route to store them in:<br />

var route = [<br />

new google.maps.LatLng(37.7671, -122.4206),<br />

new google.maps.LatLng(34.0485, -118.2568)<br />

];<br />

That’s really all the information you need to create a polyline. Now all you have to do is call the<br />

constructor for the Polyline class, add the route arrays to it, and then add the polyline to the map. Let’s<br />

take it step-by-step and start with creating the Polyline object (see Table 8-2).<br />

Table 8-2. Definition of the Polyline Constructor<br />

Constructor<br />

Polyline(options?:PolylineOptions)<br />

Description<br />

Creates a Polyline object<br />

The Polyline object takes one argument, and that is an object of type PolylineOptions.<br />

PolylineOptions has several properties, but only one is required. That’s the property path. The path<br />

property takes an array of google.maps.LatLng objects. That’s exactly what you have in the route array<br />

that you just prepared.<br />

159

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!