1. HTML5 GEOLOCATION
API
KELOMPOK 10 :
• SAFIQ NABIGHOH A. 12650011
• SYAFRUDIN 12650039
• LANDI BAKHRI K. 12650046
2. 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.
3. LOKASI GEOGRAFIS
OVERVIEW
The 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
4. BROWSER COMPATIBILITY
The 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.
5. 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])
6. 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.
7. BEGINNER RECIPE:
DETERMINING YOUR LOCATION WITH A SIMPLE
GETCURRENTPOSITION
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";
}
8. • 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.
9.
10. LOCATION PRIVACY
Knowing 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.
11. INTERMEDIATE RECIPE:
MAPPING A LOCATION WITH
GETCURRENTPOSITION
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.
12. 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.
14. 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.
15. 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.
16.
17. 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.
18. 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};
19.
20. 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.
21. 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.
22. 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
23.
24. 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.
25.
26. SUMMARY
The 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.
Selama bertahun-tahun, website telah menggunakan informasi lokasi untuk memberikan pengalaman pengguna yang ditingkatkan, seperti di mana toko terdekat adalah atau peristiwa di daerah Anda. Lokasi data telah dikumpulkan dengan menggunakan alamat IP browser dan pencocokan dalam database atau hanya meminta pengguna untuk lokasi mereka. Dengan smartphone dan built-in GPS, ada peningkatan yang signifikan dalam aplikasi yang lokasi-sadar. Dengan HTML5 dan Geolocation API, ada metode yang mudah dan cukup handal dimana website dan aplikasi web dapat mengakses lokasi browser. Dalam bab ini, Anda akan belajar tentang objek Geolocation API dan metode dalam serangkaian resep untuk mengambil informasi lokasi perangkat browser untuk digunakan dalam aplikasi Anda.
Kemampuan untuk mengidentifikasi informasi lokasi browser, apakah laptop-atau mobile berbasis, memberikan informasi kunci yang dapat digunakan untuk berbagai fungsi, termasuk yang berikut: Menampilkan posisi browser pada peta Menampilkan informasi lokasi-spesifik atau tempat tujuan Menambahkan data lokasi ke kontribusi pengguna seperti ulasan tempat atau foto
The Geolocation API yang masih muda, tetapi mengingat nilai itu berlaku, definisi API sedang diadopsi dengan cepat oleh berbagai browser. Tabel 10.1 daftar dukungan browser saat ini untuk Geolocation API.
Fungsi dasar dari Geolocation API adalah untuk menemukan lokasi saat browser di dunia. Metode getCurrentPosition memberikan informasi ini kepada Anda dalam panggilan asynchronous JavaScript. Penting untuk dicatat bahwa panggilan yang menentukan lokasi di JavaScript asynchronous di alam. Kebanyakan JavaScript dilakukan serentak atau dalam program utama f rendah. Dengan pemanggilan metode asynchronous, JavaScript melakukan panggilan di latar belakang dan kemudian mengembalikan hasil ke fungsi ketika proses selesai. Dengan memiliki panggilan API sebagai panggilan asynchronous, query dapat ditampilkan kepada pengguna tanpa menghalangi pengolahan sisa halaman. Metode getCurrentPosition mengambil posisi saat ini untuk browser dan mengambil satu parameter yang diperlukan (sukses callback nama fungsi) dan dua parameter opsional (kesalahan fungsi callback dan Pilihan posisi objek): getCurrentPosition (successCallback [, errorCallback] [, positionOptions])
Parameter getCurrentPosition meliputi berikut ini: successCallback: Fungsi untuk mengeksekusi dan lulus koordinat errorCallback: (pilihan) Fungsi untuk menangani setiap kesalahan yang terjadi Pilihan: Pilihan (pilihan) Sebuah objek untuk menangani bagaimana posisi diambil Karena panggilan untuk getCurrentPosition adalah asynchronous, metode perlu diberitahu yang berfungsi untuk keberhasilan dan kegagalan potensial akan dieksekusi ketika metode telah selesai. Mari kita melompat dan menemukan lokasi Anda sekarang dengan resep.
Dalam resep ini, halaman akan menggunakan metode getCurrentPosition dengan fungsi keberhasilan callback untuk menentukan lokasi Anda saat ini dan menampilkan properti dari objek posisi kembali. Gunakan langkah-langkah dan kode pada Listing 10.1 untuk membuat resep ini: Buat halaman HTML kosong dengan div (disebut btnFindMe) dan Cari saya tombol, yang akan memanggil fungsi FindMe saat diklik. Menambahkan fungsi FindMe dalam satu set tag script dengan kode berikut untuk memeriksa Geolocation API, dan kemudian memanggil metode getCurrentPosition:
Menambahkan fungsi geoSuccess yang akan menangani callback sukses dari permintaan getCurrentPosition. Tambahkan div kedua (disebut MyLocation) ke HTML di mana Anda akan menampilkan informasi posisi kembali dari getCurrentPosition.
Mengetahui lokasi browser, dan dengan demikian lokasi orang melihat browser, dapat dianggap sebagai informasi pribadi. Metode untuk memungkinkan pengguna untuk berbagi informasi lokasi pribadi mereka adalah melalui tindakan otorisasi, seperti yang Anda lihat dalam resep pertama ini. Sampai pengguna baik memungkinkan atau menolak akses ke lokasi, panggilan API getCurrentPosition akan ditahan. Ini adalah alasan utama bahwa panggilan ini dilakukan melalui metode asynchronous sehingga sisa halaman tidak "block" menunggu otorisasi pengguna atau balasan. Anda mungkin bertanya-tanya pada saat ini apa yang terjadi jika pengguna tidak memberikan otorisasi untuk informasi atau kali informasi lokasi out. Di sinilah parameter pengendali kesalahan dari getCurrentPosition datang ke dalam bermain dan apa yang Anda akan melihat dalam resep berikutnya.
Dalam resep ini, Anda akan menggunakan metode getCurrentPosition untuk mengambil lokasi browser dan peta pada peta Google pada halaman. Anda akan mencakup dalam resep handler kesalahan dalam kasus kesalahan dikembalikan dari metode getCurrentPosition (yang Anda akan menyebabkan terjadi segera setelah Anda memiliki halaman bekerja dengan benar). Mirip dengan resep sebelumnya, ketika beban halaman, pengguna dapat mengklik tombol Peta Me yang akan memicu metode getCurrentPosition. Setelah Anda menerima panggilan, Anda kemudian akan menggunakan garis lintang dan bujur untuk membuat sebuah instance dari peta Google dengan spidol dan jendela info untuk koordinat dan kota dan negara. Kota dan negara berasal dari objek alamat Mozilla dan tidak akan tersedia di browser lainnya. Jika Anda ingin menampilkan alamat fisik yang sesuai di browser lain, maka Anda akan perlu menggunakan reverse geocoding, yang akan Anda lihat dalam resep lain dalam bab ini.
Memanfaatkan materi sebelumnya, dan mengubah tombol untuk Petakan Saya dan fungsi dipanggil untuk mapMe. Sertakan tag script Google Maps JavaScript API V3 Overlay (perhatikan bahwa dengan V3 dari Google Maps kit, Anda tidak lagi memerlukan kunci pengembang): Memodifikasi permintaan getCurrentPosition untuk menambahkan fungsi pengendali kesalahan:? Navigator.geolocation.getCurrentPosition (geoSuccess, geoErrorHandler); Menambahkan fungsi geoErrorHandler geoErrorHandler (error), yang akan menangani setiap kesalahan yang dikembalikan oleh permintaan getCurrentPosition. Update bagian tubuh div HTML mencerminkan keadaan yang pada Listing 10,2 untuk memiliki wadah termasuk mapCanvas, tombol mapMe, dan MyLocation.
Pengendali kesalahan memungkinkan Anda untuk menangkap kesalahan kembali dan mengambil tindakan yang sesuai. Sebuah kesalahan umum, PERMISSION_DENIED, hasil dari pengguna tidak memberikan akses ke informasi yang diperlukan oleh panggilan API Geolocation pada halaman. Untuk melihat kesalahan ini, kembali halaman Anda, dan ketika browser meminta Anda untuk memungkinkan akses ke informasi lokasi, memilih untuk tidak berbagi atau melarang akses ke lokasi Anda. Pengendali kesalahan geoErrorHandler akan disebut dengan objek kesalahan posisi yang dikirimkan ke sana. Posisi objek kesalahan, berjudul kesalahan dalam kode kita, akan mencakup dua atribut: kode dan pesan. Kode yang ditunjukkan sebelumnya adalah konstanta numerik yang mendefinisikan jenis kesalahan, sementara pesan itu mungkin mengandung pesan string opsional bagi Anda sebagai pengembang untuk mendapatkan pemahaman yang lebih tentang mengapa kesalahan terjadi. Dalam hal ini, karena pengguna telah diberi akses ke informasi lokasi, kode kesalahan PERMISSION_DENIED akan disediakan, dan Anda dapat menampilkan pesan Anda sendiri.
Tips ini akan menggunakan getCurrentPosition terlebih dahulu menemukan lokasi browser Anda dan kemudian menghitung jarak ke satu set poin, sebaliknya geocode posisi Anda, dan menampilkan informasi ini kepada pemirsa. Untuk lebih mengontrol informasi lokasi yang disediakan, Anda akan menggunakan parameter ketiga metode getCurrentPosition, PositionOptions. PositionOptions adalah obyek dilewatkan ke metode getCurrentPosition sebagai parameter dan memungkinkan Anda untuk memiliki kontrol atas perilaku metode. Hal ini dapat menguntungkan mengingat jenis aplikasi Anda bekerja dengan. Sebagai contoh, jika Anda bekerja pada sebuah aplikasi restoran berbasis lokasi untuk ruang mobile, maka akurasi normal lokasi dikembalikan mungkin terlalu luas untuk kebutuhan anda. Anda dapat mengatur tiga pilihan dalam PositionOptions dari getCurrentPosition, seperti yang ditunjukkan pada Tabel 10.3.
Ketika halaman load, fungsi setLocation akan dipanggil, yang akan memicu metode getCurrentPosition menggunakan satu set pilihan. Setelah Anda menerima panggilan, Anda kemudian akan menggunakan garis lintang dan bujur untuk membuat sebuah instance dari peta Google, sebaliknya geocode koordinat, dan menghitung jarak ke berbagai kota.
Tambahkan metode panggilan setLocation ke atribut onload tubuh, dan menambahkan fungsi setLocation, pastikan untuk menyertakan posisi pilihan objek.
Update tag Google Maps JavaScript API V3 Overlay script untuk memuat perpustakaan geometri yang akan digunakan untuk perhitungan jarak:
Menambahkan fungsi reverseGeoCode yang mengambil garis lintang dan bujur titik Anda dan mengambil informasi alamat dari geocoder Google.
Menambahkan fungsi calculateDistance yang menggunakan computeDistanceBetween untuk menghitung jarak ke London, New York, dan San Francisco.
Update bagian tubuh div HTML mencerminkan keadaan yang pada Listing 10.3 memiliki wadah, termasuk mapCanvas, informasi lokasi, dan divs jarak kota.
Ketika halaman load, Anda menggunakan metode getCurrentPosition untuk mengambil koordinat lintang dan bujur tetapi dengan beberapa pilihan kunci berlalu. Sebuah objek berjudul posOptions dibuat dan kemudian diteruskan ke getCurrentPosition. Di posOptions, Anda menetapkan opsi usia maksimal untuk 60000, sama dengan satu menit, dan batas waktu sampai 30 detik (30000). Ini memberitahu getCurrentPosition untuk menarik hanya dari lokasi cache sebelumnya jika usia informasi lokasi kurang dari satu menit tua. Timeout membatasi lamanya waktu yang diperbolehkan untuk getCurrentPosition untuk mengambil posisi: posOptions var = {maximumAge: 60000, batas waktu: 30000};
Browser yang pengunjung Anda menggunakan dalam beberapa kasus akan yang berbasis mobile. Hal ini tidak jarang melihat orang-orang berjalan menyusuri jalan, naik kereta bawah tanah, atau bergerak sementara mendapatkan informasi tentang lingkungan mereka atau lokasi mereka. Metode getCurrentPosition memberikan objek posisi sekali saat dipanggil. Namun, sebagai orang bergerak di sekitar, itu akan lebih baik untuk "mengikuti" lokasi. Di sinilah dua metode baru, watchPosition dan clearWatch, dari Geolocation API berguna.
Metode watchPosition sangat mirip dengan getCurrentPosition dan mengambil parameter yang sama. Ketika metode watchPosition dipanggil, browser akan membuat tugas latar belakang dan memberikan ID referensi proses menonton sebagai keuntungan. Tugas background akan mengambil posisi saat ini, mengirim lokasi ke keberhasilan panggilan balik, dan kemudian mengatur timer untuk melihat posisi. Setiap kali timer dipicu dan lokasi baru yang diambil, lokasi ini kemudian dibandingkan untuk melihat apakah itu "signifikan" yang berbeda. Jika lokasi baru secara signifikan berbeda dari yang terakhir, maka fungsi keberhasilan callback disebut dengan informasi lokasi baru.
successCallback: Fungsi untuk mengeksekusi dan melewati objek lokasi ketika lokasi baru diidentifikasi oleh browser
errorCallback: (pilihan) Fungsi untuk menangani setiap kesalahan yang terjadi
Pilihan: (pilihan) Sebuah pilihan objek untuk menangani bagaimana posisi diambil clearWatch (watchId)
Parameter dari metode clearWatch adalah sebagai berikut:
watchId: ID referensi lama untuk proses menonton untuk mengakhiri
Perbedaan Pengecekan ini akan berdasarkan pada kebutuhan Anda sendiri, tapi tips ini menunjukkan bagaimana Anda dapat menyaring titik lokasi dengan menggunakan beberapa perhitungan jarak yang cepat karena perubahan lokasi.
Buat halaman HTML dengan tombol Mulai Menonton dan Clear Watch, seperti ditunjukkan pada Listing 10.4
Sertakan script untuk Google Maps JavaScript API V3 Overlay dengan library geometri dan variabel global yang akan terus melihat ID, peta, polyline, dan lintang terakhir dan bujur.
Menambahkan fungsi initMap di script, dan mengatur acara buka untuk membuka fungsi initMap.
Tambahkan fungsi startWatch dan clearWatch
Tambahkan fungsi successCallback dan errorCallback
The Geolocation API menyediakan antarmuka yang mudah untuk menambahkan fungsi mengetahui lokasi tertentu dan posisi untuk situs web dan aplikasi. Beberapa solusi yang dapat dirancang meliputi berikut ini:
Menampilkan lokasi informasi spesifik
Proximity awareness
Penyesuaian dinamis untuk lokal, misalnya bahasa dan mata uang
Pengintegrasian Peta dan rute
Data geotagging, gambar, dan item lainnya dengan informasi lokasi
Dalam bab ini, Anda belajar metode getCurrentPosition, watchPosition, dan clearWatch bersama dengan kesuksesan dan kesalahan callback dari metode ini. Kemungkinannya tak terbatas, dan itu adalah menarik untuk memiliki option ini sekarang dalam browser.