Google Map Javascript API 取得目前位置

Google Map Javascript API 取得目前位置

大家好 ... 好久沒寫部落格了,先來做一個小小的分享好了

今天要跟大家分享的是,如何在Google Map Javascript API 中取得目前位置

範例如下:

javascript:

var initialLocation;
var taipei = new google.maps.LatLng(25.09108, 121.5598);
var browserSupportFlag =  new Boolean();

function initialize() {
  var myOptions = {
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  
  // Try W3C Geolocation (Preferred)
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  }
  // Browser doesn't support Geolocation
  else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }
  
  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("地圖定位失敗");
    } else {
      alert("您的瀏覽器不支援定位服務");
    }
	initialLocation = taipei;
    map.setCenter(initialLocation);
  }
}

解釋:

01~03 宣告目前所需使用的變數

06~09 宣告地圖選項(Zoom/Type)等等

10 初始化地圖

13 判斷瀏覽器是否支援位置服務

14~20 處理瀏覽器位置資訊,並將地圖定位至此

24~25 處理瀏覽器不支援位置服務之邏輯

28~36 處理錯誤訊息

若errorFlag為True,則瀏覽器支援位置服務但取得目前位置失敗

若errorFlag為False,則瀏覽器不支援位置服務

完整html:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var initialLocation;
var taipei = new google.maps.LatLng(25.09108, 121.5598);
var browserSupportFlag =  new Boolean();

function initialize() {
  var myOptions = {
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
  
  // Try W3C Geolocation (Preferred)
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  }
  // Browser doesn't support Geolocation
  else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }
  
  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("地圖定位失敗");
    } else {
      alert("您的瀏覽器不支援定位服務");
    }
	initialLocation = taipei;
    map.setCenter(initialLocation);
  }
}
</head>
<body onload="initialize()">
  <div id="map_canvas" style="width:1024px; height:768px"></div>
</body>
</html>

 

一個很簡單的小處理,謝謝大家