2013-06-29 54 views
28

我已經看過這個問題已被問過的各種其他時間,但我不能把手指放在哪裏我要錯了,這​​是我的代碼:谷歌地圖API - 客戶端當前位置的中心地圖

<html> 
<head> 
    <title> Map </title> 
    <style> 
     html, body, #map-canvas { 
     margin: 0; 
     padding: 0; 
     height: 500px; 
     width: 800px;} 
    </style> 
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> 
    <script> 
     var map; 
     function initialize() 
     { 
      var myLatlng1 = new google.maps.LatLng(53.65914, 0.072050); 

      var mapOptions = 
      { 
       zoom: 10, 
       center: myLatlng1, 
       mapTypeId: google.maps.MapTypeId.ROADMAP 
      }; 
      var map = new google.maps.Map(document.getElementById('map-canvas'), 
      mapOptions); 


      <?php 
       $sql = mysql_query("SELECT * FROM data ORDER BY ID DESC"); 
       while($row =mysql_fetch_array($sql)) 
       { 
        $desc = $row['DESCRIPTION']; 
        $location = $row['LOCATION']; 
        $counter += 1; 
       ?> 

      var marker = new google.maps.Marker({ 
       position: new google.maps.LatLng(<?php echo $location; ?>), 
       map: map, 
       title: '<?php echo $desc; ?>', 
       icon: '/image/cam.png' 
      }); 

      navigator.geolocation.getCurrentPosition(showPosition); 
     } 

     var showPosition = function (position) 
      { 
       map.setCenter(new google.maps.LatLng(position.coords.latitude, position.coords.longitude), 16); 

      } 

     google.maps.event.addDomListener(window, 'load', initialize); 

    </script> 
</head> 

它最初將中心設置爲myLatlng1,底部的代碼將其設置爲用戶的當前位置並沒有做任何事情,有什麼想法?

在此先感謝。

+0

https://github.com/onury/geolocator找到用戶位置並自動創建一個帶有居中標記的地圖。 –

回答

79

嘗試使用下面的代碼來獲取用戶的當前位置(地理位置):

if (navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function (position) { 
     initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); 
     map.setCenter(initialLocation); 
    }); 
} 

對於展示一個例子,我已經刪除你的PHP代碼。檢查此JSFiddle

希望你明白。

+1

感謝您的一段代碼。它真的幫了我 – Dibish

+1

感謝兄弟非常有幫助有我喜歡然後 –

+1

它工作得很好..謝謝親愛的:) –

相關問題