<!DOCTYPE html> <html> <head> <title>獲取當前位置</title> </head> <body> <script> // 使用HTML5 Geolocation API獲取當前位置的經緯度 if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else { alert("該瀏覽器不支持Geolocation API"); } function showPosition(position) { var lat = position.coords.latitude; var lng = position.coords.longitude; // 將經緯度傳遞給後端PHP腳本來獲取周邊POI資訊 window.location.href = 'get_poi.php?lat=' + lat + '&lng=' + lng; } </script> </body> </html>在上述代碼中,我們使用`navigator.geolocation.getCurrentPosition`方法來獲取當前位置的經緯度,並將其傳遞給`get_poi.php`文件。
<?php $lat = $_GET['lat']; $lng = $_GET['lng']; // 替換為自己的高德地圖開發者Key $key = 'YOUR_AMAP_KEY'; $url = 'https://restapi.amap.com/v3/place/around?key=' . $key . '&location=' . $lng . ',' . $lat . '&output=json&radius=1000&keywords='; $response = file_get_contents($url); // 解析JSON響應 $result = json_decode($response, true); if ($result['status'] == '1') { // 獲取返回的POI資訊 $pois = $result['pois']; // 處理POI資訊 foreach ($pois as $poi) { echo $poi['name'] . '<br> '; echo $poi['address'] . '<br> '; echo '類型:' . $poi['type'] . '<br> '; echo '<br> '; } } else { echo '獲取周邊POI資訊失敗'; } ?>
在這段代碼中,我們從前端獲取經緯度,通過$_GET數組傳遞給PHP後端。然後構建高德地圖API的URL,利用file_get_contents函數調用API並獲取響應。
返回的響應是一個JSON格式的字符串,使用json_decode函數將其解析為關聯數組。接下來,我們遍歷POI數組,輸出每個POI的名稱、地址和類型。
注意:請替換代碼中的YOUR_AMAP_KEY為您自己的高德地圖開發者Key。
在瀏覽器中打開獲取經緯度的HTML文件,允許瀏覽器獲取當前位置。瀏覽器將重定向到get_poi.php ,並通過URL傳遞經緯度。服務器根據經緯度調用高德地圖API,返回周邊POI信息。
這篇文章為開發者提供了一個簡單的示例,幫助你在PHP項目中集成高德地圖API,獲取並處理周邊POI信息。希望本文對你有所幫助!