如何将地图置于当前用户位置的中心位置(地理位置

时间:2012-10-28 12:22:46

标签: javascript geolocation location point

我有这个代码,我想以用户位置为中心,因为现在它把它放在我所拥有的坐标(丹麦哥本哈根上面)的中心,并且它是固定的。我需要让我的代码将地图置于用户位置的中心并显示它周围的点

function initialize() {

var locations = [
    ['kastelet', 55.6911, 12.5939],
    ['norebro', 55.6883, 12.5597],
    ['noreport', 55.6832, 12.5714],
    ['edisikvosi', 55.678272, 12.503643,],
    ['Sentosa', 55.713207, 12.526474,]
    ];

var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 12,
    center: new google.maps.LatLng(55.6750, 12.5687),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var infowindow = new google.maps.InfoWindow();

var marker, i;

for (i = 0; i < locations.length; i++) {
    marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
    });

    google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
            infowindow.setContent(locations[i][0]);
            infowindow.open(map, marker);
        }
    })(marker, i));
}

// Check if user support geo-location
if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var geolocpoint = new google.maps.LatLng(latitude, longitude);

        var mapOptions = {
            zoom: 8,
            center: geolocpoint,
            mapTypeId: google.maps.MapTypeId.HYBRID
        }
        // Place a marker
        var geolocation = new google.maps.Marker({
            position: geolocpoint,
            map: map,
            title: 'Your geolocation',
            icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
        });
    });
}
}
google.maps.event.addDomListener(window, 'load', initialize);​

1 个答案:

答案 0 :(得分:0)

使用map.setCenter

 .....
 navigator.geolocation.getCurrentPosition(function(position) {
        var latitude = position.coords.latitude;
        var longitude = position.coords.longitude;
        var geolocpoint = new google.maps.LatLng(latitude, longitude);
          map.setCenter(geolocpoint );//line added for setting center
......