Using the Geolocation API
Secure context
This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.
Geolocation API ใช้เพื่อเรียกคืนตำแหน่งของผู้ใช้เพื่อให้สามารถใช้เพื่อแสดงตำแหน่งโดยใช้ API การแมป บทความนี้อธิบายพื้นฐานของวิธีใช้
วัตถุตำแหน่งทางภูมิศาสตร์
Geolocation APIสามารถใช้ได้ผ่านทาง navigator.geolocation
วัตถุ
หากวัตถุมีอยู่บริการระบุตำแหน่งทางภูมิศาสตร์จะพร้อมใช้งาน คุณสามารถทดสอบการมีตำแหน่งทางภูมิศาสตร์ได้ดังนี้:
if('geolocation' in navigator) {
/* geolocation is available */
} else {
/* geolocation IS NOT available */
}
รับตำแหน่งปัจจุบัน
ในการรับตำแหน่งปัจจุบันของผู้ใช้คุณสามารถเรียกใช้วิธี getCurrentPosition()
สิ่งนี้จะเริ่มต้นคำขอแบบอะซิงโครนัสเพื่อตรวจหาตำแหน่งของผู้ใช้และสอบถามฮาร์ดแวร์การจัดตำแหน่งเพื่อรับข้อมูลที่ทันสมัย เมื่อกำหนดตำแหน่งแล้วฟังก์ชันการเรียกกลับที่กำหนดไว้จะถูกดำเนินการ คุณสามารถเลือกที่จะให้ฟังก์ชั่นการติดต่อกลับที่สองที่จะดำเนินการหากเกิดข้อผิดพลาด พารามิเตอร์ตัวที่สามเป็นตัวเลือกคือวัตถุตัวเลือกที่คุณสามารถตั้งค่าอายุสูงสุดของตำแหน่งที่ส่งคืนเวลารอคำขอและถ้าคุณต้องการความแม่นยำสูงสำหรับตำแหน่ง
หมายเหตุ:โดยค่าเริ่มต้น getCurrentPosition()
พยายามตอบเร็วที่สุดเท่าที่จะทำได้ด้วยความแม่นยำต่ำ มันจะมีประโยชน์ถ้าคุณต้องการคำตอบอย่างรวดเร็วโดยไม่คำนึงถึงความถูกต้อง อุปกรณ์ที่มีจีพีเอส, ตัวอย่างเช่นสามารถใช้เวลาเป็นนาทีหรือมากกว่าที่จะได้รับสัญญาณ GPS, ข้อมูลเพื่อความแม่นยำน้อย (ที่ตั้งของทรัพย์สินทางปัญญาหรือ WiFi) getCurrentPosition()
อาจจะกลับไป
navigator.geolocation.getCurrentPosition((position) => {
doSomething(position.coords.latitude, position.coords.longitude);
});
ตัวอย่างด้านบนจะทำให้doSomething()
ฟังก์ชันทำงานเมื่อได้รับตำแหน่ง
ดูตำแหน่งปัจจุบัน
หากข้อมูลตำแหน่งเปลี่ยนแปลง (โดยการเคลื่อนไหวของอุปกรณ์หรือข้อมูลทางภูมิศาสตร์ที่แม่นยำกว่ามาถึง) คุณสามารถตั้งค่าฟังก์ชั่นการโทรกลับที่ถูกเรียกพร้อมกับข้อมูลตำแหน่งที่อัปเดตนั้น สิ่งนี้ทำได้โดยใช้ฟังก์ชัน watchPosition()
ซึ่งมีพารามิเตอร์อินพุตเหมือนกับ getCurrentPosition()
. ฟังก์ชั่นการโทรกลับถูกเรียกหลายครั้งทำให้เบราว์เซอร์สามารถอัปเดตตำแหน่งของคุณในขณะที่คุณย้ายหรือให้ตำแหน่งที่แม่นยำยิ่งขึ้นเนื่องจากใช้เทคนิคต่าง ๆ ในการระบุตำแหน่งของคุณ ฟังก์ชั่นการเรียกกลับข้อผิดพลาดซึ่งเป็นตัวเลือกเช่นเดียวกับมันgetCurrentPosition()
สามารถเรียกซ้ำ
Note: You can use watchPosition()
without an initial getCurrentPosition()
call.
const watchID = navigator.geolocation.watchPosition((position) => {
doSomething(position.coords.latitude, position.coords.longitude);
});
The watchPosition()
method returns an ID number that can be used to uniquely identify the requested position watcher; you use this value in tandem with the clearWatch()
method to stop watching the user's location.
navigator.geolocation.clearWatch(watchID);
Fine tuning the response
Both getCurrentPosition()
and watchPosition()
accept a success callback, an optional error callback, and an optional PositionOptions
object.
This object allows you to specify whether to enable high accuracy, a maximum age for the returned position value (up until this age it will be cached and reused if the same position is requested again; after this the browser will request fresh position data), and a timeout value that dictates how long the browser should attempt to get the position data for, before it times out.
A call to watchPosition
could look like:
function success(position) {
doSomething(position.coords.latitude, position.coords.longitude);
}
function error() {
alert('Sorry, no position available.');
}
const options = {
enableHighAccuracy: true,
maximumAge: 30000,
timeout: 27000
};
const watchID = navigator.geolocation.watchPosition(success, error, options);
Describing a position
The user's location is described using a GeolocationPosition
object instance, which itself contains a GeolocationCoordinates
object instance.
The GeolocationPosition
instance contains only two things, a coords
property that contains the GeolocationCoordinates
instance, and a timestamp
property that contains a DOMTimeStamp
instance representing the time at which the position data was retrieved.
The GeolocationCoordinates
instance contains a number of properties, but the two you'll use most commonly are latitude
and longitude
, which are what you need to draw your position on a map. Hence many Geolocation success callbacks look fairly simple:
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// Do something with your latitude and longitude
}
You can however get a number of other bits of information from a GeolocationCoordinates
object, including altitude, speed, what direction the device is facing, and an accuracy measure of the altitude, longitude, and latitude data.
Handling errors
The error callback function, if provided when calling getCurrentPosition()
or watchPosition()
, expects a GeolocationPositionError
object instance as its first parameter. This object type contains two properties, a code
indicating what type of error has been returned, and a human-readable message
that describes what the error code means.
You could use it like so:
function errorCallback(error) {
alert(`ERROR(${error.code}): ${error.message}`);
};
Examples
In the following example the Geolocation API is used to retrieve the user's latitude and longitude. If sucessful, the available hyperlink is populated with an openstreetmap.org
URL that will show their location.
HTML
<button id = "find-me">Show my location</button><br/>
<p id = "status"></p>
<a id = "map-link" target="_blank"></a>
JavaScript
function geoFindMe() {
const status = document.querySelector('#status');
const mapLink = document.querySelector('#map-link');
mapLink.href = '';
mapLink.textContent = '';
function success(position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
status.textContent = '';
mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
mapLink.textContent = `Latitude: ${latitude} °, Longitude: ${longitude} °`;
}
function error() {
status.textContent = 'Unable to retrieve your location';
}
if(!navigator.geolocation) {
status.textContent = 'Geolocation is not supported by your browser';
} else {
status.textContent = 'Locating…';
navigator.geolocation.getCurrentPosition(success, error);
}
}
document.querySelector('#find-me').addEventListener('click', geoFindMe);