2013-10-25 54 views
4

我正在使用Google Maps API v3地理位置來獲取用戶的實際位置。我發現這個職位從谷歌開發者:谷歌地圖API v3地理位置不能在Google Chrome中工作

這裏我的代碼(相當於谷歌地圖例子的代碼):

<head> 
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true"></script> 

<script> 
// Note: This example requires that you consent to location sharing when 
// prompted by your browser. If you see a blank space instead of the map, this 
// is probably because you have denied permission for location sharing. 

var map; 

function initialize() { 
    var mapOptions = { 
    zoom: 6, 
    mapTypeId: google.maps.MapTypeId.ROADMAP 
    }; 

    map = new google.maps.Map(document.getElementById('map-canvas'), 
     mapOptions); 

    // Try HTML5 geolocation 
    if(navigator.geolocation) { 
    navigator.geolocation.getCurrentPosition(function(position) { 
     var pos = new google.maps.LatLng(position.coords.latitude, 
             position.coords.longitude); 

     var infowindow = new google.maps.InfoWindow({ 
     map: map, 
     position: pos, 
     content: 'Location found using HTML5.' 
     }); 

     map.setCenter(pos); 
    }, function() { 
     handleNoGeolocation(true); 
    }); 
    } else { 
    // Browser doesn't support Geolocation 
    handleNoGeolocation(false); 
    } 
} 

function handleNoGeolocation(errorFlag) { 
    if (errorFlag) { 
    var content = 'Error: The Geolocation service failed.'; 
    } else { 
    var content = 'Error: Your browser doesn\'t support geolocation.'; 
    } 

    var options = { 
    map: map, 
    position: new google.maps.LatLng(60, 105), 
    content: content 
    }; 

    var infowindow = new google.maps.InfoWindow(options); 
    map.setCenter(options.position); 
} 

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

<body> 
    <div id="container"> 
     <div class="entry-content"> 
      <div class="blogtitle">IT</div><p>&nbsp;</p></td><td> </td><td><p>&nbsp;</p></td></tr></tbody></table><p>&nbsp;</p> 
      <div id="map-canvas"></div><!-- map-canvas end --> 
     </div><!-- entry-content end --> 
    </div><!-- container end --> 
</body> 

這在Firefox,但不是很細谷歌瀏覽器&蘋果瀏覽器。我認爲,因爲Chrome瀏覽器& Safari是webkit瀏覽器。但我不知道如何解決它。

有人可以幫我嗎?

+0

它有什麼不起作用?你沒有看到地圖,你無法獲得用戶的位置,你會得到一個JavaScript錯誤? – duncan

+0

出現錯誤:'錯誤:地理位置服務失敗.'然後標記點在俄羅斯某處的森林中(我在瑞士......) – Tyler

回答

2

我發現this

It appears this is a security restriction for the file protocol. Looks like you are going to need to host it locally from a server.

我測試你的代碼在本地服務器,它只是正常工作。 希望我能幫上忙。

+0

嗯。謝謝,你知道我可以如何從本地服務器託管它?一個例子? – Tyler

+0

取決於您正在使用的操作系統。我使用MAMP(http://www.mamp.info/)用於OSX。如果您使用的是Windows,請檢查XAMP。只需將你的html/php/css /任何文件放入htdocs文件夾並啓動服務器即可。這裏有一個關於MAMP的小常見問題(http://www.mamp.info/en/documentation/faq.html) – zitscher

+0

你的意思是XAMPP?我正在使用Windows。在我的公司,我們不使用XAMPP。我們使用IIS。你知道如何以這種方式託管它? – Tyler