谷歌地图用户位置未加载

时间:2018-08-20 13:35:00

标签: javascript google-maps

我可以创建一个网页,其中包含特定城市中许多企业的名称,地址,经纬度和经度,并将其放入我页面上的嵌入式Google地图中。与数据库的连接有效,将标记放置在地图上有效,但是我无法从任何示例(包括Google开发人员页面上的示例)中弄清楚的是如何使用用户的位置而不是googlemap中的默认坐标.js文件。我在这里想念什么?

var map;
var geocoder;

function loadMap() {

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
    var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
    };
    map = new google.maps.Map(document.getElementById('map'),
        {
            zoom: 14,
            center: pos
        });
});
}

     var marker = new google.maps.Marker({
    //   position: pune,
         map: map
     });

     var cdata = JSON.parse(document.getElementById('data').innerHTML); 
     geocoder = new google.maps.Geocoder();
     codeAddress(cdata);

     var allData = JSON.parse(document.getElementById('allData').innerHTML);
     showAllHonda(allData)
}
function showAllHonda(allData) {
var infoWind = new google.maps.InfoWindow;
Array.prototype.forEach.call(allData, function(data){
    var content = document.createElement('div');
    var strong = document.createElement('strong');
    strong.textContent = data.name;
    content.appendChild(strong);


    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(data.lat, data.lng),
        map: map
    });
    marker.addListener('click', function(){
        infoWind.setContent(content);
        infoWind.open(map, marker);
    })

})
}


function codeAddress(cdata) {
Array.prototype.forEach.call(cdata, function(data){
    var address = data.name + ' ' + data.address;
    geocoder.geocode( { 'address': address}, function(results, status) {
        if (status == 'OK') {
            map.setCenter(results[0].geometry.location);
            var points = {};
            points.id = data.id;
            points.lat = map.getCenter().lat();
            points.lng = map.getCenter().lng();
            updateHondaWithLatLng(points);
        } else {
            alert('Geocode was not successful for the following reason: ' + status)
        }
});
});
}

1 个答案:

答案 0 :(得分:0)

要找到用户的位置,可以使用navigator.geolocation

if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
        var pos = {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        };
        map = new google.maps.Map(document.getElementById('map'),
            {
                zoom: 14,
                center: pos
            });
    });
}