移至用户位置标记

时间:2016-07-21 09:13:48

标签: javascript jquery google-maps google-maps-api-3

我有这个设置多个标记的代码,我是谷歌地图API的新手,并试图学习如何设置地图以自动显示当前用户的位置标记。我得到它的教程是在收到所有标记后设置地图中心。这是我的代码: -

<script>
var startPos, positionPromise = $.Deferred();

navigator.geolocation.getCurrentPosition(function(position) {
    startPos = position;
    $('#pok_lat').val(startPos.coords.latitude); 
    $('#pok_long').val(startPos.coords.longitude);

    positionPromise.resolve();

}, function(error) {
    alert('Error occurred. Error code: ' + error.code + '');
    // error.code can be:
    //   0: unknown error
    //   1: permission denied
    //   2: position unavailable (error response from locaton provider)
    //   3: timed out

    positionPromise.reject();

});

$(function($) {
    // Asynchronously Load the map API 
    var script = document.createElement('script');
    script.src = "//maps.googleapis.com/maps/api/js?key=SOMEAPIKEY&callback=initialize";
    document.body.appendChild(script);
});

window["initialize"] = function() {
    var map;
    var bounds = new google.maps.LatLngBounds();
    var mapOptions = {
        mapTypeId: 'roadmap'
    };

    // Display a map on the page
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    map.setTilt(45);

    // Multiple Markers LatLong
    $.when(positionPromise).then(function(){
            var lats = document.getElementById("pokemon_lat").value;
            var longi = document.getElementById("pokemon_long").value;
            console.log('Lat:'+lats+' Long:'+longi);

    var markers = [
        ['You are here!', lats,longi],
        <?php
        for ($x = 0; $x < count($pok_info); $x++) {
            if ($x < count($pok_info)) {
                $addcomma = ",";
            }
            else {
                $addcomma = "";
            }
            $pok_array[] = "['".$pok_info[$x]['name']."', ".$pok_info[$x]['lat'].",".$pok_info[$x]['long']."]".$addcomma;

        }

            $remove_comma = count($pok_array);  
            $remove_comma = $remove_comma - 1;
            $pok_array[$remove_comma] = rtrim($pok_array[$remove_comma],',');
                foreach ($pok_array as $value) {
                echo $value;
            }
        ?>
    ];

    // Info Window Content
    var infoWindowContent = [
        ['You are here!'],
        <?php
        for ($x = 0; $x < count($pok_info); $x++) {
            if ($x < count($pok_info)) {
                $addcomma = ",";
            }
            else {
                $addcomma = "";
            }
            $pok_array_info[] = "['<div class=\"info_content\"><h3>".$pok_info[$x]['name']."</h3><br><img width=\"100\" height=\"100\" src=\"".$pok_info[$x]['pic']."\"><p>".$pok_info[$x]['description']."</p>']".$addcomma;

        }

            $remove_comma = count($pok_array_info); 
            $remove_comma = $remove_comma - 1;
            $pokemon_array_info[$remove_comma] = rtrim($pok_array_info[$remove_comma],',');
                foreach ($pok_array_info as $value) {
                echo $value;
            }
        ?>
    ];

    // Pok Icons

     var pokeImage = [ 
        ['images/pokeball.png'],
        <?php

            $img_icons = array();

            for ($x = 0; $x < count($pok_info); $x++) {
                $img_icon = $pok_info[$x]['pic'];
                $img_icon = explode(".",$img_icon);
                $img_icons[] = $img_icon[0]."_small.png";
                $addcomma = ",";

            $pok_array_info_pic[] = "['".$img_icons[$x]."']".$addcomma;

        }


            $remove_comma = count($pok_array_info_pic); 
            $remove_comma = $remove_comma - 1;
            $pok_array_info[$remove_comma] = rtrim($pok_array_info_pic[$remove_comma],',');
                foreach ($pok_array_info_pic as $value) {
                echo $value;
            }

            ?>
     ];

    // Display multiple markers on a map
    var infoWindow = new google.maps.InfoWindow(), marker, i;

    // Loop through our array of markers & place each one on the map  
    for( i = 0; i < markers.length; i++ ) {
        var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
        bounds.extend(position);
        marker = new google.maps.Marker({
            position: position,
            map: map,
            title: markers[i][0],
            icon: pokeImage[i][0]   
        });

        // Allow each marker to have an info window    
        google.maps.event.addListener(marker, 'click', (function(marker, i) {
            return function() {
                infoWindow.setContent(infoWindowContent[i][0]);
                infoWindow.open(map, marker);
            }
        })(marker, i));

        map.panTo(marker.getPosition());

        // Automatically center the map fitting all markers on the screen
       //map.fitBounds(bounds);
       //console.log('Lat:'+lats)+' Long:'+parseInt(longi));
    }

    // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
    var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
        this.setZoom(14);
        google.maps.event.removeListener(boundsListener);
    });

    }, function(){
            console.log("Could not get latitude and longitude )-:");
        });

}
</script>

1 个答案:

答案 0 :(得分:0)

在未经他许可的情况下无法读取用户当前纬度经度,因此您应该使用地理位置或让用户手动输入他/她的位置。

<html>
<div id="map_canvas"></div>
</html>
    <script>
    $(document).ready(function() {
    if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(showPosition);
         }


    drawMap(document.getElementById("map_canvas"),position.coords.latitude,position.coords.longitude)
    });
    function drawMap(element, latitude, longitude)
    {
        latitude = latitude || 23.83;
        longitude = longitude || 84.31;
        var latlng = new google.maps.LatLng(latitude, longitude);
        var mapOptions = {zoom: 7, center:latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false};
        map = new google.maps.Map(element, mapOptions);
    }
    </script>

或第二种可能性: -

<html>
<input type="text" id="latitude">
<input type="text" id="longitude">
    <div id="map_canvas"></div>
    </html>
        <script>
        $(document).ready(function() {
     var latitude = document.getElementById("latitude");
     var latitude = document.getElementById("longitude");
   drawMap(document.getElementById("map_canvas"),latitude,longitude)
        });
        function drawMap(element, latitude, longitude)
        {
            latitude = latitude || 23.83;
            longitude = longitude || 84.31;
            var latlng = new google.maps.LatLng(latitude, longitude);
            var mapOptions = {zoom: 7, center:latlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false};
            map = new google.maps.Map(element, mapOptions);
        }
        </script>

但它取决于浏览器。

Currently the W3C Geolocation API is supported by the following desktop browsers:

Firefox 3.5+
Chrome 5.0+
Safari 5.0+
Opera 10.60+
Internet Explorer 9.0+
There is also support for the W3C Geolocation API on mobile devices:

Android 2.0+
iPhone 3.0+
Opera Mobile 10.1+
Symbian (S60 3rd & 5th generation)
Blackberry OS 6
Maemo

在浏览器中如果: - 在&#34;隐私&#34;部分位置部分关闭然后我们无法跟踪位置使用此地理编码,因此用户应该在浏览器中保持位置。

您只需在代码中写下它,它将以地图为中心

  var latitude = document.getElementById('pok_lat');
    var longitude = document.getElementById('pok_long'); 
    var latlng = new google.maps.LatLng(latitude, longitude);
    window["initialize"] = function() {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
            center:latlng,
            mapTypeId: 'roadmap'
        };

从Chrome 5.0开始,Geolocation API仅适用于HTTPS等安全上下文。如果您的网站托管在非安全源(例如HTTP)上,则获取用户位置的请求将不再起作用。