36

我已经看过这个问题被问到的其他各种时间,但我不能完全指出我哪里出错了,这是我的代码:

<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,而底部将其设置为用户当前位置的代码没有做任何事情,有什么想法吗?

提前致谢。

4

2 回答 2

102

尝试使用以下代码获取用户的当前位置(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

希望你能理解。

于 2013-06-29T18:27:22.677 回答
3

提供有用的地图,无论用户是否允许或拒绝浏览器的“允许位置检测?” 提示(修改默认位置以适应):

<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>
于 2018-11-23T08:55:46.653 回答