![](/img/trans.png)
[英]JavaScript Google Maps API - Center on User's Location not loading map
[英]Google maps API - Center map on client's current location
我已經看過這個問題的其他幾個問題,但我不能完全指出我出錯的地方,這是我的代碼:
<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,底部的代碼將其設置為用戶的當前位置並沒有做任何事情,任何想法?
提前致謝。
嘗試使用以下代碼獲取用戶的當前位置( GEOLOCATION ):
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
為了顯示一個例子,我刪除了你的PHP代碼。 檢查這個JSFiddle
希望你能理解。
提供有用的地圖,無論用戶是允許還是拒絕瀏覽器的“允許位置檢測?” 提示(修改默認位置以適應):
<script>
function initMap() {
gMap = new google.maps.Map(document.getElementById('map'));
navigator.geolocation.getCurrentPosition(function(position) {
// Center on user's current location if geolocation prompt allowed
var initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
gMap.setCenter(initialLocation);
gMap.setZoom(13);
}, function(positionError) {
// User denied geolocation prompt - default to Chicago
gMap.setCenter(new google.maps.LatLng(39.8097343, -98.5556199));
gMap.setZoom(5);
});
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.