HTML and CSS Reference
In-Depth Information
Create a
Map
object by calling
new google.maps.Map(document.getElementById("map"),
myOptions)
, passing in the HTML element where you want to display the map and a
Map options
object.
There are many options that can be set, but the three used for this solution are
zoom
,
mapTypeId
, and
center
. The options are fairly descriptive as to their purpose. Set
zoom
to
4
to allow the user to see the entire US. For the
mapTypeId
, use
ROADMAP
, which displays
the normal, default 2D tiles of Google Maps. The other options are
SATELLITE
,
HYBRID
, and
TERRAIN
. The
center
option indicates the location that is displayed in the
center of the map.
The latitude and longitude of Kansas, which is a central location in the US, are hard-
coded to create a
LatLng
object that can be used to set the
center
parameter. When the
Map
object is created using the
new
keyword it, automatically updates our
map div
.
The next line,
directionsRenderer = new google.maps.DirectionsRenderer();
, creates
a new
DirectionsRenderer
object that can automatically update
Map
s for us. The line
directionsRenderer.setMap(map);
doesn't do anything yet, but it tells the user to enter
an address and click the button.
In this example, refactored logic does a geolocation fallback in order to be a little more
compact and reusable:
function getLatLng(callback) {
// test for presence of geolocation
if (navigator && navigator.geolocation) {
// make the request for the user's position
navigator.geolocation.getCurrentPosition(function (position) {
// success handler
callback(position.coords.latitude, position.coords.longitude);
},
function (err) {
// handle the error by passing the callback the location from MaxMind
callback(geoip_latitude(), geoip_longitude(), true);
});
} else {
// geolocation not available, so pass the callback the location from
// MaxMind
callback(geoip_latitude(), geoip_longitude(), true);
}
}
The
getLatLng()
function takes a single callback parameter that returns the
latitude
,
longitude
, and
isMaxMind
variables.
We check for the existence of
navigator.geolocation
just like we did before, but this
time we define the
navigator.geolocation
callback handlers inline to call our common
callback function. That returns either the results of
getCurrentPosition()
or the Max-
Mind latitude and longitude.