0

GOOGLE MAPS API

I.Google place API Dịch vụ này cho phép truy vấn và tìm các thông tin trên bản đồ theo nhiều thể loại như: tìm nhà hàng, khách sạn, trường học, các địa điểm du lịch,… Với google place ta có thể tìm các địa điểm bằng những từ khóa thân thiện và gần gũi. Kết quả trả về của quá trình tìm kiếm là 1 chỉ dẫn và giới thiệu ngắn gọn về địa điểm và chi tiết về địa điểm đó.

  1. Place Nearby Search - Tìm kiếm các khu vực gần đó

a.Web API Service Develop URL: https://developers.google.com/places/documentation/search#PlaceSearchRequests Cho phép tìm kiếm trong một địa điểm được xác định. Ta có thể tinh chỉnh yêu cầu tìm kiếm bằng cách cung cấp các từ khóa hoặc yêu cầu cụ thể về các thể loại tại khu vực đó.

<!--more-->

URL request có dạng: https://maps.googleapis.com/maps/api/place/nearbysearch/output?parameters Với output có thể là json hoặc xml Tham số bắt buộc: key: Khóa do Google cung cấp. Cần kích hoạt Google Place API để sử dụng ứng dụng này. Địa chỉ cung cấp API Key: https://code.google.com/apis/console location: Kinh độ/vĩ độ trung tâm để lấy các địa điểm xung quanh. Định dạng: KinhĐộ,VĩĐộ Ví dụ: 20.9875830,105.8316770 radius: bán kính tìm kiếm, đơn vị met (tối đa 50.000m) sensor: Có sử dụng bộ định vị GPS hay không (true/false) Ví dụ : tìm các cây ATM xung quanh đường Duy Tân :

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=20.982968,105.814229&radius=2000&types=atm&sensor=false&key=AIzaSyBfQPm46M3j2joTFlHachk4RCXfeR7ZFWE Key = AIzaSyD1zSRhwykOgyFaYMecyHpsaW1R1BVgiiE

Results[0].Geometry.Location (kinh độ/vĩ độ của địa điểm): 20.9875830,105.8316770 Results[0].icon (icon của loại địa điểm) Results[0].name (tên địa điểm): "ATM - Vietcombank", Results[0].rating  (đánh giá): Chưa có Results[0].reference (Mã địa điểm để xem chi tiết) Results[0].types (địa điểm này thuộc các loại danh mục gì): [ "atm", "finance", "establishment" ] Results[0].vicinity (vùng lân cận): "Định Công"

b. Google Places Nearby Search Javascript API:

Places Nearby Search được sử dụng trong gói google.maps.places.PlacesService và gọi phương thức nearbySearch (request, callback) để thực hiện:

service = new google.maps.places.PlacesService(map); service.nearbySearch(request, callback); <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Google Maps JavaScript API v3 Example: Place Search</title> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places"></script>

<style>

map {

height: 400px; width: 600px; border: 1px solid #333; margin-top: 0.6em; } </style>

<script> var map; var infowindow;

function initialize() { // Khởi tạo bản đồ // Vị trí trung tâm 20.9875830,105.8316770 (Định Công) var pyrmont = new google.maps.LatLng(20.9875830,105.8316770);

// khởi tạo bản đồ vào div#map map = new google.maps.Map(document.getElementById('map'), { mapTypeId: google.maps.MapTypeId.ROADMAP, // ROADMAP displays the normal, default 2D tiles of Google Maps. // SATELLITE displays photographic tiles. // HYBRID displays a mix of photographic tiles and a tile layer for prominent features (roads, city names). // TERRAIN displays physical relief tiles for displaying elevation and water features (mountains, rivers, etc.). center: pyrmont, zoom: 15 // Zoom hiện tại });

// Tạo đối tượng request var request = { location: pyrmont, // Tìm từ vị trí trung tâm radius: 500, // Bán kính 500m types: ['atm'] // Tìm tất cả nhà hàng }; // Hiển thị thông tin về địa điểm infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); // Thực hiện gọi hàm nearbySearch để tìm những atm lân cận và trả về thực hiện // hàm callback service.nearbySearch(request, callback); } function customSearch(){ // Khởi tạo bản đồ // Vị trí trung tâm 20.9875830,105.8316770 (Định Công) var pyrmont = new google.maps.LatLng(20.9875830,105.8316770);

// khởi tạo bản đồ vào div#map map = new google.maps.Map(document.getElementById('map'), { mapTypeId: google.maps.MapTypeId.ROADMAP, center: pyrmont, zoom: 15 });

var place_type = document.getElementById('place_type'); var selected_type = place_type.options[place_type.selectedIndex].value; // Tạo đối tượng request var request = { location: pyrmont, // Tìm từ vị trí trung tâm radius: document.getElementById('radius').value, // Bán kính 500m types: [selected_type] // Tìm tất cả atm }; // Hiển thị thông tin về địa điểm infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); // Thực hiện gọi hàm nearbySearch để tìm những atm lân cận và trả về thực hiện // hàm callback service.nearbySearch(request, callback);

} function callback(results, status) { if (status == google.maps.places.PlacesServiceStatus.OK) { for (var i = 0; i < results.length; i++) { // Duyệt từng địa điểm và đánh dấu lên bản đồ createMarker(results[i]); } } } // Hàm đánh dấu lên bản đồ từ 1 đối tượng địa điểm place function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.maps.Marker({ map: map, position: place.geometry.location });

google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(place.name); infowindow.open(map, this); }); }

google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <!-- Tạo custom các control để thực hiện tìm tùy chỉnh --> Loại địa điểm: <select id="place_type"> <option value="atm">ATM</option> <option value="school">Trường học</option> <option value="store">Cửa hàng</option> <option value="hospital">Bệnh viện</option> </select> Bán kính: <input type="text" id="radius" /><br/> <input type="button" onclick="customSearch()" value="Tìm" /> <div id="map"></div> <div id="text"> </div> </body> </html>

2.Text search request a.Web API Service

Develop URL: https://developers.google.com/places/documentation/search#Text SearchRequests Dịch vụ cung cấp các thông tin các địa điểm dựa trên chuỗi truy vấn tự nhiên, ví dụ “Ngân Hàng VietComBank”, “Cửa hàng quấn áo phố Huế”. Sau khi gởi lệnh truy vấn, dịch vụ sẽ trả về địa điểm khớp với chuỗi truy vấn và những thông tin về những địa điểm đó. URL request có dạng:  https://maps.googleapis.com/maps/api/place/textsearch/output?parameters Với output có thể là json hoặc xml Tham số bắt buộc: key: Khóa do Google cung cấp. Cần kích hoạt Google Place API để sử dụng ứng dụng này. query: chuỗi truy vấn. Ví dụ: “nhà hàng ở Hồ Tây”, “bệnh viện ở Hai Bà Trưng”,… sensor: Có sử dụng bộ định vị GPS hay không (true/false) language: Xuất kết quả về theo ngôn ngữ, xem các “language code” tại: https://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 Ví dụ: language=vi (Việt Nam) VD: Tìm các bệnh viện ở HN https://maps.googleapis.com/maps/api/place/textsearch/json?query=Bệnh+Viện+HN&sensor=false&language=vi&key=AIzaSyBfQPm46M3j2joTFlHachk4RCXfeR7ZFWE

b. Google Places Text Search Javascript API

service = new google.maps.places.PlacesService(map); service.nearbySearch(request, callback);

  <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet"> <title>Google Maps JavaScript API v3 Example: Place Search Pagination</title> <script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script> <script> var map, placesList;

function initialize() { // Vị trí hiển thị khi bản đồ hiển thị lần đầu tiên // Vị trí 20.9875830,105.8316770 (Định Công) var pyrmont = new google.maps.LatLng(20.9875830,105.8316770); // Khởi tạo bản đồ map = new google.maps.Map(document.getElementById('map_canvas'), { mapTypeId: google.maps.MapTypeId.ROADMAP, center: pyrmont, zoom: 17 });

// Khởi tạo đối tượng request var request = { query: 'Bệnh Viện Hà Nội' // ta chỉ cần từ khóa truy vấn cho google place text search }; // Hiển thị các địa điểm tìm được lên list có ul#places placesList = document.getElementById('places'); // request đến service var service = new google.maps.places.PlacesService(map); // Gọi hàm callback trả về quả về service.textSearch(request, callback); // đổi hàm sử dụng API Google Place text search }

function callback(results, status, pagination) { if (status != google.maps.places.PlacesServiceStatus.OK) { return; } else { // Nếu có kết quả thì thực hiện gắn các nhãn lên bản đồ createMarkers(results);

// google hỗ trợ phân trang nếu quá nhiều địa điểm trong kết quả if (pagination.hasNextPage) { var moreButton = document.getElementById('more');

moreButton.disabled = false;

google.maps.event.addDomListenerOnce(moreButton, 'click', function() { moreButton.disabled = true; pagination.nextPage(); }); } } }

// Hàm gắn các nhãn dựa vào đối tượng place function createMarkers(places) { var bounds = new google.maps.LatLngBounds();

for (var i = 0, place; place = places[i]; i++) { var image = new google.maps.MarkerImage( place.icon, new google.maps.Size(71, 71), new google.maps.Point(0, 0), new google.maps.Point(17, 34), new google.maps.Size(25, 25));

var marker = new google.maps.Marker({ map: map, icon: image, title: place.name, position: place.geometry.location });

placesList.innerHTML += '<li>' + place.name + '</li>';

bounds.extend(place.geometry.location); } map.fitBounds(bounds); }

google.maps.event.addDomListener(window, 'load', initialize); </script> <style>

results {

font-family: Arial, Helvetica, sans-serif; position: absolute; right: 5px; top: 50%; margin-top: -200px; height: 400px; width: 200px; padding: 5px; z-index: 5; border: 1px solid #999; background: #fff; } h2 { font-size: 22px; margin: 0 0 5px 0; } ul { list-style-type: none; padding: 0; margin: 0; height: 341px; width: 200px; overflow-y: scroll; } li { background-color: #f1f1f1; padding: 10px; text-overflow: ellipsis; white-space: nowrap; overflow: hidden; } li:nth-child(odd) { background-color: #fcfcfc; }

more {

width: 100%; margin: 5px 0 0 0; } </style> </head> <body> <div id="map_canvas"></div> <div id="results"> <h2>Results</h2> <ul id="places"></ul> <button id="more">More results</button> </div> </body> </html>

II. Distance Matrix Web API

  1. Webservice API

Url develop : https://developers.google.com/maps/documentation/distancematrix/ Google Distance Matrix API là dịch vụ cung cấp cho người sử dụng tính khoảng cách và thời gian đi lại giữa điểm bắt đầu và điểm kết thúc. Distance maxtrix request có dạng: http://maps.googleapis.com/maps/api/distancematrix/output?parameters

Tham số bắt buộc: origins: Một hay nhiều địa chỉ của “địa điểm đi” được cách nhau bởi “|”. Ta có thể truyền vào là 1 chuỗi địa chỉ thì service tự chuyển qua giá trị vĩ độ/kinh độ; nếu truyền vào là giá trị vĩ độ/kinh độ thì lưu ý không có khoảng cách trắng giữa. origins=Duy+Tân+Cầu Giấy +HN| 20.9875830,105.8316770 destinations: Tương tự địa điểm đi “origins”, “destinations” là một hay nhiều địa chỉ của “địa điểm đến” sensor: Có sử dụng bộ định vị GPS hay không (true/false) Các tham số khác: mode: Dùng để tính thời gian di chuyển từ “điểm đi” đến “điểm đến” mode=driving: tham số mặc định, di chuyển bằng phương tiện chuẩn trên đường bộ mode=walking: đi bộ mode=bicycling: đi xe đạp language: Xuất kết quả về theo ngôn ngữ, xem các “language code” tại: https://spreadsheets.google.com/pub?key=p9pdwsai2hDMsLkXsoM05KQ&gid=1 Ví dụ: language=vi (Việt Nam) avoid: tùy chọn tránh phí cầu đường hoặc các đường cao tốc avoid=tolls: trạm thu phí avoid=highways: đường cao tốc units: đơn vị trả về units= metric (mặc định): tính bằng kilometers và meters units= imperial: tính bằng dặm và bước đi. Dữ liệu trả về:

  1. Javascript API

Url develop : https://developers.google.com/maps/documentation/javascript/distancematrix Ngoài webservice, Google API còn cung cấp thêm dịch vụ Javascript Distance Matrix cho phép người dùng tương tác và sử dụng Google Map bằng javascript ngay trên ứng dụng của mình bằng cách gọi phương thức callback để thực hiện yêu cầu và trả kết quả. Để sử dụng ta chèn đoạn javascript sau vào header: <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

Ta có thể sử dụng đối tượng google.maps.DistanceMatrixService  và thực hiện phương thức DistanceMatrixService.getDistanceMatrix() để yêu cầu và gọi phương thức callback trả kết quả. Các tham số: origins, destinations, trabelMode (mode), avoidHightways (avoid=hightways), avoidTolls (avoid=tools) giống II.1 – Các tham số

Phương thức Callback: phương thức DistanceMatrixService.getDistanceMatrix() sau khi thực hiện sẽ trả về đối tượng DistanceMatrixResponse cùng với trạng thái status và gọi callback truyền đối tượng response và trạng thái status Phương thức callback sau sẽ in ra khoảng cách và thời gian đi từng địa điểm trong tập origins và từng địa điểm đến trong tập destinations

<!DOCTYPE html> <html> <head> <title>Google Maps API v3 Example: Distance Matrix</title> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>

<style> body { margin: 20px; font-family: courier, sans-serif; font-size: 12px; }

map {

height: 480px; width: 640px; border: solid thin #333; margin-top: 20px; } </style>

<script>

var map; var geocoder; var bounds = new google.maps.LatLngBounds(); var markersArray = [];

var origin1 = new google.maps.LatLng(20.9875830,105.8316770); // Địa Điểm thứ nhất theo tọa độ var origin2 = 'Định công, Hà Nội';  // Địa điểm đi thứ hai var destinationA = 'Hai Bà Trưng, Hà Nội, Việt Nam'; // Địa điểm đến thứ nhất var destinationB = 'Cầu Giấy, Quan Hoa, Hà Nội, Việt Nam'; // Địa điểm đến thứ hai

// Icon địa điểm đến hiển thị trên bản đồ var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000'; // Icon địa điểm đi hiển thị trên bản đồ var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

// Hàm khởi tạo bản đồ function initialize() { var opts = { center: new google.maps.LatLng(20.9875830,105.8316770), // Kinh độ/ Vĩ độ trung tâm của bản đồ zoom: 10, mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById('map'), opts); geocoder = new google.maps.Geocoder(); }

// hàm tính toán và gọi service Google javascript API function calculateDistances() { // Khởi tạo Distance matrix service var service = new google.maps.DistanceMatrixService(); service.getDistanceMatrix( { origins: [origin1,origin2], destinations: [destinationA,destinationB], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false }, callback); }

function calculateDistances2() { // Khởi tạo Distance matrix service var service = new google.maps.DistanceMatrixService(); origin1 = document.getElementById('from').value; destinationA = document.getElementById('to').value; service.getDistanceMatrix( { origins: [origin1], destinations: [destinationA], travelMode: google.maps.TravelMode.DRIVING, unitSystem: google.maps.UnitSystem.METRIC, avoidHighways: false, avoidTolls: false }, callback); }

// Hàm được gọi sau khi calculateDistances thực hiện xong và trả về kết quả response và status function callback(response, status) { // Nếu kết quả trả về với status không phải = OK if (status != google.maps.DistanceMatrixStatus.OK) { // Báo lỗi alert('Error was: ' + status); } else {

// Lấy các địa chỉ đi từ var origins = response.originAddresses; // Lấy các địa chỉ đến var destinations = response.destinationAddresses; var outputDiv = document.getElementById('outputDiv'); outputDiv.innerHTML = ''; deleteOverlays(); // Duyệt danh sách địa chỉ đi từ for (var i = 0; i < origins.length; i++) { // Lấy kết quả ứng với danh sách đi từ var results = response.rows[i].elements; addMarker(origins[i], false); // Với mỗi danh sách địa chỉ đi đến ứng với địa chỉ đi từ thứ i for (var j = 0; j < results.length; j++) { addMarker(destinations[j], true); // Xuất kết quả outputDiv.innerHTML += origins[i] + ' đến ' + destinations[j]

  • ': ' + results[j].distance.text + ' trong '
  • results[j].duration.text + '<br>'; } } } }

function addMarker(location, isDestination) { var icon; if (isDestination) { icon = destinationIcon; } else { icon = originIcon; } geocoder.geocode({'address': location}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { bounds.extend(results[0].geometry.location); map.fitBounds(bounds); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location, icon: icon }); markersArray.push(marker); } else { alert('Geocode was not successful for the following reason: '

  • status); } }); }

function deleteOverlays() { if (markersArray) { for (i in markersArray) { markersArray[i].setMap(null); } markersArray.length = 0; } }

</script> </head> <body onload="initialize()"> <div id="inputs"> Đi từ: <input type="text" id="from" /> Đi đến: <input type="text" id="to" /><br/> <p><button type="button" onclick="calculateDistances2();">Tính khoảng cách 2</button></p>

<p><button type="button" onclick="calculateDistances();">Tính khoảng cách</button></p> </div> <div id="outputDiv"></div> <div id="map"></div> </body> </html>

III.Directions Service 1.Webservice API

URL develop: https://developers.google.com/maps/documentation/directions/ Tương tự trên nhưng chỉ rõ đường đi , thời gian. http://maps.googleapis.com/maps/api/directions/json?origin=Duy+Tân+Cầu++Giấy+HN&destination=Hai+Bà+Trưng+HN &sensor=false&avoid=highway

  1. JavaScript API

URL develop : https://developers.google.com/maps/documentation/javascript/directions?hl=vi Ngoài webservice, Google API còn cung cấp thêm dịch vụ Javascript Directions Cho phép người dùng có thể tương tác và sử dụng Google Maps bằng javascript ngay trên ứng dụng của mình bằng các phương thức calcRoute() để thực hiện yêu cầu và lấy kết quả trả về.

Để sử dụng ta chèn vào đoạn javascript sau vào header <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> Hoặc bạn có thể đăng kí một KEY riêng cho mình rồi chèn theo dạng sau: <script http://maps.googleapis.com/maps/api/js?key=AIzaSyBHc01iDz0w0xh3uZShTzKWMO6dBE-WMPw&sensor=false&callback=initialize </script> Ta có thể sử dụng đối tượng google.maps.DirectionsService() và thực hiện phương thức directionsDisplay.setDirections() để yêu cầu và gọi phương thức calcRoute() để trả về kết quả. var directionsService = new google.maps.DirectionsService(); function calcRoute() {

var start = document.getElementById('start').value;//điểm bắt đầu var end = document.getElementById('end').value;//điểm kết thúc var request = { origin: start, destination: end, travelMode: google.maps.DirectionsTravelMode.TRANSIT//phương thức di chuyển }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response);//tìm kiếm các đường di chuyển } }); }

<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Google Maps JavaScript API v3 Example: Directions Complex</title> <link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet"> <style>

directions-panel {

height: 100%; float: right; width: 390px; overflow: auto; }

map-canvas {

margin-right: 400px; }

control {

background: #fff; padding: 5px; font-size: 14px; font-family: Arial; border: 1px solid #ccc; box-shadow: 0 2px 2px rgba(33, 33, 33, 0.4); display: none; }

@media print {

map-canvas {

height: 500px; margin: 0; }

directions-panel {

float: none; width: auto; } } </style> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script><!-- Gọi service --> <script> var directionDisplay; var directionsService = new google.maps.DirectionsService();//gọi direction service

function initialize() { directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { zoom: 15,//zoom hiệnt tại mapTypeId: google.maps.MapTypeId.ROADMAP,//Kiểu hiển thị map center: new google.maps.LatLng(20.9875830,105.8316770)//địa điểm mặc định }; var map = new google.maps.Map(document.getElementById('map_canvas'),//hiển thị các thông báo khi chỉ dẫn mapOptions); directionsDisplay.setMap(map); directionsDisplay.setPanel(document.getElementById('directions-panel'));//hiển thị các kết quả chỉ dẫn

var control = document.getElementById('control'); control.style.display = 'block'; map.controls[google.maps.ControlPosition.TOP].push(control); }

function calcRoute() { var start = document.getElementById('start').value;//điểm bắt đầu do người dùng chọn var end = document.getElementById('end').value;//điểm kết thúc do người dùng chọn var request = { origin: start, destination: end, travelMode: google.maps.DirectionsTravelMode.TRANSIT//phương thức di chuyển }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(response);//tìm kiếm các đường di chuyển } }); }

google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="control"> <strong>Điểm bắt đầu: </strong> <select id="start" onchange="calcRoute();"> <option value="Đại học khoa học tự nhiên TP.HCM">Đại học KHTN</option> <option value="Bệnh viện Từ Dũ">Bệnh viện Từ Dũ</option> <option value="Đại học Sài Gòn">Đại học Sài Gòn</option> <option value="Ngã tư Hàng Xanh">Ngã tư Hàng Xanh</option> <option value="Chợ Bến Thành">Chợ Bến Thành</option> <option value="Bệnh Viện K, Quán Sứ">Bệnh Viện K, Quán Sứ</option> // Thử Nghiệm với đường đi HN </select> <strong>Điểm kết thúc: </strong> <select id="end" onchange="calcRoute();"> <<option value="Đại học khoa học tự nhiên TP.HCM">Đại học KHTN</option> <option value="Bệnh viện Từ Dũ">Bệnh viện Từ Dũ</option> <option value="Đại học Sài Gòn">Đại học Sài Gòn</option> <option value="Ngã tư Hàng Xanh">Ngã tư Hàng Xanh</option> <option value="Chợ Bến Thành">Chợ Bến Thành</option> <option value="Bệnh viện Trung ương Quân Đội 108, Trần Hưng Đạo">Bệnh viện Trung ương Quân Đội 108</option>  // Thử Nghiệm với đường đi HN </select> </div> <div id="directions-panel"></div> <div id="map_canvas"></div> </body> </html>

IV.Geocoding Service 1.Webservice API

URL devolop : https://developers.google.com/maps/documentation/geocoding/?hl=vi Geocoding cho phép chuyển đổi giữa các địa chỉ và các mô tả khác vào vĩ độ/kinh độ của bản đồ toạ độ. Điều này cung cấp cho chúng ta một khung cảnh giúp dễ nhận biết các vị trí và toạ độ được sử dụng trong các dịch vụ dựa trên vị trí và hoạt động trên bản đồ. Để thực hiện việc này lớp Geocoder gọi phương thức cho dịch vụ web. Lớp Geocoder cung cấp hai chức năng truy cập mã địa lí như sau: Forward Geocodeding: tìm vĩ độ và kinh độ dựa vào địa chỉ. Reverse Geocodeding: tìm địa chỉ dựa vào vĩ độ và kinh độ.

Một Geocoding API có dạng như sau: https://maps.googleapis.com/maps/api/ geocode /output?parameters output có thể là: XML hoặc JSON Các thông số address: địa chỉ mà bạn muốn tìm. latlng: vĩ độ/kinh độ mà bạn muốn tìm Ví dụ: address = Định + Công + Hà +Nội tatlng = (20.9875830,105.8316770) sensor: =false nếu bạn không muốn dùng định vị vị trí, = true nếu bạn muốn sử dụng định vị trị trí. component: giới hạn khu vực để trả về kết quả địa chỉ trong vùng đó. Nó có thể là: country: mã quốc gia, route: tuyến đường bounds: khoanh vùng cho kết quả trả về. language: ngôn ngữ hiển thị khi trả về. region: kết quả trả về trong một khu vực( thường là mã quốc gia) Dữ liệu trả về Trạng thái trả về OK: không có lỗi xảy ra, địa chỉ được phân tích thành công và ít nhất một mã địa chỉ được trả về ZERO_RESULTS: cho biết các mã địa chỉ được phân tích thành công nhưng không trả về kết quả. OVER_QUERY_LIMIT: truy vấn vượt quá giới hạn REQUEST_DENIED: yêu cầu bị từ chối INVALID_REQUEST: yêu cầu không hợp lệ Kết quả trả về Kết quả trả về gồm những thông tin như sau: types[]: cho biết loại địa điểm trả về đó là loại gì: thành phố, đường,… formatted_address: là một chuỗi chứa các thông tin địa chỉ mà con người có thể đọc từ vị trí này. address_components[]: một mảng chứa các thành phần địa chỉ riêng biệt bao gồm các thông tin như: type[]: loại địa chỉ, long_name: mô tả, short_name: tên viết tắt. geometry: chứa các thông tin như: location: có giá trị kinh độ/vĩ độ, location_type: lưu trữ giá trị bổ sung về vị trí, viewport: chứa khung nhìn về vị trí, bounds: bao gồm các địa chỉ gần kề có thể trả về partial_match: cho biết kết quả trả về có nằm trong phạm vi phù hợp hay không Ví dụ: Forward Geocoder cho vị trí: Tòa nhà việt Á Duy Tân Dịch Vọng Cầu Giấy  Hà Nội sử dụng JSON, không sử dụng thiết bị định vị và hiển thị ra tiếng Việt: http://maps.googleapis.com/maps/api/geocode/json?address=Duy+Tân+Dịch+Vọng+Cầu+Giấy+Hà+Nội&sensor=false&language=vi 2. Javascript API

URL develop : https://developers.google.com/maps/documentation/javascript/geocoding?hl=vi Ngoài webservice, Google API còn cung cấp thêm dịch vụ Javascript Geocoding cho  phép người dùng tương tác và sử dụng Google Maps bằng javascript ngay trên ứng dụng của mình bằng cách gọi phương thức: geocode() thực hiện yêu cầu và trả về kết quả. Để sử dụng API của Google Maps ta chèn đoạn script sau: <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> Ta có sử dụng đối tượng google.maps.Geocoder() và thực hiện phương thức geocode() để trả về kết quả. var geocoder=new google.maps.Geocoder();//đối tượng geocoder function codeAddress() {//phương phức lấy geocoder để trả về kết quả var address = document.getElementById('address').value;//địa chỉ geocode geocoder.geocode( { 'address': address/địa chỉ geocoding/}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { alert('Geocode was not successful for the following reason: ' + status); } });

<!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Google Maps JavaScript API v3 Example: Geocoding Simple</title> <link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet"> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script><!--Gọi geocode service--> <script> var geocoder; var map; function initialize() { geocoder = new google.maps.Geocoder();//phương thức geocoder var latlng = new google.maps.LatLng(20.9875830,105.8316770);//đặt địa điểm hiện tại của bản đồ var mapOptions = { zoom: 16,//để độ nhìn center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP//loại bản đồ } map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); }

function codeAddress() {//phương phức lấy geocoder var address = document.getElementById('address').value; geocoder.geocode( { 'address': address/địa chỉ geocoding/}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { map.setCenter(results[0].geometry.location); var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); } else { alert('Geocode was not successful for the following reason: ' + status); } }); } </script> </head> <body onload="initialize()"> <div> <input id="address" type="textbox" value="Sydney, NSW"> <input type="button" value="Geocode" onclick="codeAddress()"> </div> <div id="map_canvas" style="height:90%;top:30px"></div> </body> </html>

 

  <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <title>Google Maps JavaScript API v3 Example: Reverse Geocoding</title> <link href="https://google-developers.appspot.com/maps/documentation/javascript/examples/default.css" rel="stylesheet"> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script><!--gọi service--> <script> var geocoder; var map; var infowindow = new google.maps.InfoWindow(); var marker; function initialize() { geocoder = new google.maps.Geocoder();//phương thức gecoder var latlng = new google.maps.LatLng(20.9875830,105.8316770);//địa chỉ hiện tại của bản đồ var mapOptions = { zoom: 16, center: latlng, mapTypeId: 'roadmap' } map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions); }

function codeLatLng() {//phương thức geocoding thành địa điểm var input = document.getElementById('latlng').value; var latlngStr = input.split(',', 2); var lat = parseFloat(latlngStr[0]); var lng = parseFloat(latlngStr[1]); var latlng = new google.maps.LatLng(lat, lng); geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { map.setZoom(11); marker = new google.maps.Marker({ position: latlng, map: map }); infowindow.setContent(results[1].formatted_address); infowindow.open(map, marker); } else { alert('No results found'); } } else { alert('Geocoder failed due to: ' + status); } }); } </script> </head> <body onload="initialize()"> <div> <input id="latlng" type="textbox" value="40.714224,-73.961452"> </div> <div> <input type="button" value="Reverse Geocode" onclick="codeLatLng()"> </div> <div id="map_canvas" style="height: 90%; top:60px; border: 1px solid black;"></div> </body> </html>

 

END


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí