27
HTML5 GEOLOCATION API KELOMPOK 10 : SAFIQ NABIGHOH A. 12650011 SYAFRUDIN 12650039 LANDI BAKHRI K. 12650046

Html5 geolocation api

Embed Size (px)

Citation preview

Page 1: Html5 geolocation api

HTML5 GEOLOCATION API

KELOMPOK 10 :

• SAFIQ NABIGHOH A. 12650011• SYAFRUDIN 12650039• LANDI BAKHRI K. 12650046

Page 2: Html5 geolocation api

OVERVIER

For years, websites have used location information to provide enhanced user

experiences, such as where the closest store is or events in your area. The location data

has been gathered by using a browser’s IP address and matching it in a database or just

asking the user for their location. With smartphones and built-in GPS, there is a

significant increase in apps that are location-aware. With HTML5 and the Geolocation

API, there is an easy and fairly reliable method by which websites and web applications

can access a browser’s location. In this chapter, you will learn about the Geolocation

API objects and methods in a series of recipes to retrieve the browser device’s location

information for use in your application.

Page 3: Html5 geolocation api

LOKASI GEOGRAFIS OVERVIEWThe ability to identify the location information of a browser, whether laptop- or

mobile-based, provides key information that can be used for a variety of

functionality, including the following:

o Displaying the browser’s position on a map

o Displaying location-specific information or points of interest

o Adding location data to user contributions such as place reviews or photographs

Page 4: Html5 geolocation api

BROWSER COMPATIBILITYThe Geolocation API is still young, but given the value it holds, the API definition is being

adopted rapidly by the various browsers. Table 10.1 lists the current browser support for the

Geolocation API.

Page 5: Html5 geolocation api

WHERE IN THE WORLD: GETCURRENTPOSITION

The basic function of the Geolocation API is to find the current location of the browser in the world. The

getCurrentPosition method provides this information to you in a JavaScript asynchronous call. It is important to note

that the calls that determine location in JavaScript are asynchronous in nature. Most JavaScript is performed

synchronously or in the main program f low. With asynchronous method calls, JavaScript performs the call in the

background and then returns the results to a function when the process is complete. By having the API call as an

asynchronous call, the query can be displayed to the user without blocking the processing of the rest of the page.

The getCurrentPosition method retrieves the current position for the browser and takes one required parameter (a

success callback function name) and two optional parameters (an error callback function and a position options

object):

getCurrentPosition (successCallback [, errorCallback] [, positionOptions])

Page 6: Html5 geolocation api

The parameters of the getCurrentPosition include the following:

• successCallback: The function to execute and pass the coordinates to

• errorCallback: (Optional) The function to handle any errors that occurred

• options: (Optional) An options object to handle how the position is retrieved

Since the call to getCurrentPosition is asynchronous, the method needs to be told which functions

for success and potential failure will be executed when the method has completed. Let’s jump in

and find your location now with a recipe.

Page 7: Html5 geolocation api

BEGINNER RECIPE:DETERMINING YOUR LOCATION WITH A SIMPLEGETCURRENTPOSITION

In this recipe, the page will use the getCurrentPosition method with a success callback function to determine

your current location and display the properties of the position object returned. Use these steps and the code in

Listing 10.1 to create this recipe:

• Create a blank HTML page with a div (called btnFindMe) and the Find Me button, which will call the

findMe function when clicked.

• Add the findMe function in a set of script tags with the following code to check for the Geolocation API,

and then call the getCurrentPosition method:

if (navigator.geolocation) {

navigator.geolocation.getCurrentPosition(geoSuccess);

} else {

document.getElementById('myLocation').innerHTML =

"Geolocation API Not Supported";

}

Page 8: Html5 geolocation api

• Add the geoSuccess function that will handle the successful callback from

the getCurrentPosition request.

• Add a second div (called myLocation) to the HTML in which you will

display the returned position information from the getCurrentPosition.

Page 9: Html5 geolocation api
Page 10: Html5 geolocation api

LOCATION PRIVACYKnowing the location of a browser, and thus the location of the person viewing the browser, can be

considered to be private information. The method for allowing users to share their private location

information is through an authorization action, as you saw in this first recipe. Until the user either allows or

denies access to the location, the getCurrentPosition API call will be on hold. This is a key reason that this

call is performed via an asynchronous method so that the rest of the page does not “block” waiting for the

user authorization or reply.

You may be wondering at this point what happens if the user does not provide authorization for the

information or the location information times out. This is where the error handler parameter of the

getCurrentPosition comes into play and what you will look at in the next recipe.

Page 11: Html5 geolocation api

INTERMEDIATE RECIPE:MAPPING A LOCATION WITHGETCURRENTPOSITION

In this recipe, you will use the getCurrentPosition method to retrieve the location of the browser and map it on a

Google map on the page. You will include in the recipe an error handler in case an error is returned from the

getCurrentPosition method (which you will cause to happen as soon as you have the page working correctly).

Similar to the prior recipe, when the page loads, the user can click the Map Me button that will trigger the

getCurrentPosition method. Once you receive the call, you will then use the latitude and longitude coordinates to

create an instance of a Google map with a marker and an info window for the coordinates and city and state.

The city and state comes from the Mozilla address object and will not be available in other browsers. If you want to

show the corresponding physical address in other browsers, then you will need to use reverse geocoding, which you

will see in another recipe in this chapter.

Page 12: Html5 geolocation api

1. Leverage the previous recipe, and change the button to Map Me and the function called to

mapMe.

2. Include the Google Maps JavaScript API V3 Overlay script tag (note that with V3 of the

Google Maps kit, you no longer need a developer key):

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

3. Modify the getCurrentPosition request to add the error handler function:

navigator.geolocation.getCurrentPosition(geoSuccess, geoErrorHandler);

4. Add the geoErrorHandler function geoErrorHandler(error), which will handle any errors

that are returned by the getCurrentPosition request.

5. Update the HTML body div sections to mirror those in Listing 10.2 to have a container

including a mapCanvas, the mapMe button, and myLocation.

Page 13: Html5 geolocation api

YOUR LOCATION MAPPED IN A GOOGLE MAP

Page 14: Html5 geolocation api

The error handler allows you to catch an error returned and take the appropriate action. A common error,

PERMISSION_DENIED, results from the user not granting access to the information required by the

Geolocation API call on the page. To view this error, reload your page, and when the browser asks for you to

allow access to the location information, choose to not share or disallow access to your location. The error

handler geoErrorHandler will be called with a position error object passed to it. The position error object, titled

error in our code, will include two attributes: code and message. The code shown previously is a numerical

constant that defines the type of error, while the message may contain an optional string message for you as the

developer to gain more understanding as to why the error occurred. In this case, since the user has denied

access to the location information, the PERMISSION_DENIED error code will be provided, and you can

display your own message.

Page 15: Html5 geolocation api

INTERMEDIATE RECIPE:DETERMINING DISTANCE WITH POSITIONOPTIONS

This recipe will use getCurrentPosition to first locate your browser’s location and then calculate

the distance to a set of points, reverse geocode your position, and display this information to the

viewer. To better control the location information provided, you will use the third parameter of

the getCurrentPosition method, PositionOptions. PositionOptions is an object passed to the

getCurrentPosition method as a parameter and allows you to have some control over the

behavior of the method. This can be beneficial given the type of application you are working

with. As an example, if you are working on a location-based restaurant application for the mobile

space, then the normal accuracy of the returned location may be too broad for your needs. You

can set three options in the PositionOptions of getCurrentPosition, as shown in Table 10.3.

Page 16: Html5 geolocation api
Page 17: Html5 geolocation api

When the page loads, the setLocation function will be called, which will trigger the getCurrentPosition method using a set of

options. Once you receive the call, you will then use the latitude and longitude coordinates to create an instance of a Google

map, reverse geocode the coordinates, and calculate the distance to various cities.

1. Add the setLocation method call to the body onload attribute, and add the setLocation function, making sure to include

the position options object.

2. Update the Google Maps JavaScript API V3 Overlay script tag to load the geometry library that will be used for the

distance calculation:

<script src="http://maps.google.com/maps/api/js?sensor=false&libraries=geometry">

3. Add the reverseGeoCode function that takes your latitude and longitude point and retrieves the address information from

a Google geocoder.

4. Add the calculateDistance function that uses computeDistanceBetween to calculate the distance to London, New York,

and San Francisco.

5. Update the HTML body div sections to mirror those in Listing 10.3 to have a container, including a mapCanvas, location

information, and city distance divs.

Page 18: Html5 geolocation api

When the page loads, you use the getCurrentPosition method to retrieve the

latitude and longitude coordinates but with some key options passed. An object

titled posOptions is created and then passed to the getCurrentPosition. In the

posOptions, you set the maximum age option to 60000, equal to one minute, and

the timeout to 30 seconds (30000). This tells the getCurrentPosition to pull only

from a previously cached location if the age of the location information is less

than one minute old. The timeout limits the length of time allowed for the

getCurrentPosition to retrieve the position:

var posOptions = {maximumAge:60000, timeout:30000};

Page 19: Html5 geolocation api
Page 20: Html5 geolocation api

ADVANCED RECIPE:FOLLOWING A MOVING LOCATION WITH WATCH POSITION

The browser that your visitor is using in many cases will be mobile-based. It is not

uncommon to see people walking down the street, riding the subway, or otherwise

moving about while getting information about their surroundings or their locations. The

getCurrentPosition method provides a position object once when called. However, as a

person moves around, it would be nice to “follow” the location. This is where two new

methods, watchPosition and clearWatch, of the GeoLocation API

are useful.

Page 21: Html5 geolocation api

The watchPosition method is very similar to the getCurrentPosition and

takes the same parameters. When the watchPosition method is called, the

browser will create a background task and provide a reference ID to a watch

process as a return. The background task will retrieve the current position,

send the location to the succes callback, and then set a timer to watch the

position. Each time the timer is triggered and a new location is retrieved, the

location is then compared to see whether it is “significantly” different. If the

new location is significantly different from the last, then the success callback

function is called with the new location information.

Page 22: Html5 geolocation api

THE PARAMETERS OF THE WATCHPOSITION METHOD ARE AS FOLLOWS:• successCallback: The function to execute and pass the location object to

when a new location is identified by the browser

• errorCallback: (Optional) The function to handle any errors that

occurred

• options: (Optional) An options object to handle how the position is

retrieved clearWatch (watchId)

The parameter of the clearWatch method is as follows:

• watchId: The long ID reference to the watch process to end

Page 23: Html5 geolocation api
Page 24: Html5 geolocation api

This difference check will be based on your own needs, but this recipe shows how you

can filter location points using some quick distance calculations as the location

changes.

• Create the HTML page with the Start Watch and Clear Watch buttons, as shown in

Listing 10.4.

• Include the script for the Google Maps JavaScript API V3 Overlay with the

geometry library and the global variables that will hold the watch ID, map,

polyline, and last latitude and longitude coordinates.

• Add the initMap function in the script, and set the load event to launch the initMap

function.

• Add the startWatch and clearWatch functions.

• Add the successCallback and errorCallback functions.

Page 25: Html5 geolocation api
Page 26: Html5 geolocation api

SUMMARYThe Geolocation API provides an easy interface for adding location-specific and position aware

functionality to websites and applications. Some of the solutions that can be designed include the

following:

• Display of location specific information

• Proximity awareness

• Dyn amicadjustment to a locale, such as language and currency

• Map and route integration

• Geotagging data, pictures, and other items with location information

In this chapter, you learned the getCurrentPosition, watchPosition, and clearWatch methods along

with the success and error callbacks from these methods. The possibilities are endless, and it is

exciting to have this option now in browsers.

Page 27: Html5 geolocation api

TERIMAKASIH ... HTML5 GEOLOCATION API