javascript Google Map API 如何为当前位置设置标记

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21976869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:07:52  来源:igfitidea点击:

Google Map API how to set marker for current location

javascriptgoogle-mapsgoogle-maps-api-3geolocation

提问by Kiddo

I'm learning google map API and stuck at this problem when i'm trying to add the current coordinate to an array. Here is my code:

我正在学习谷歌地图 API 并在尝试将当前坐标添加到数组时遇到了这个问题。这是我的代码:

var locations = [];

In initialize() i have:

在 initialize() 我有:

function initialize() {
    infowindow = new google.maps.InfoWindow();
    var myOptions = {
        zoom: 10,
        mapTypeControl: true,
        navigationControl: true,
    }
    map = new google.maps.Map(document.getElementById("map"), myOptions);

    add_location('Place 1', 37.2846372, -123.3270422);
    set_current_location();
    set_markers(new google.maps.LatLngBounds(), map);
}

The first marker is set, while the set_current_location() doesn't seem to work. Here is the rest of the code:

第一个标记已设置,而 set_current_location() 似乎不起作用。下面是代码的其余部分:

// add new location to the locations array
function add_location(description, lastitude, longtitude) {
    locations.push([description, lastitude, longtitude]);
}

// Set all the markers in the location arrays and bound/frame the map
function set_markers(bounds, map) {
    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
        });
        bounds.extend(marker.position);
        google.maps.event.addListener(marker, 'click', (function (marker, i) {
            return function () {
                infowindow.setContent(locations[i][0]);
                infowindow.open(map, marker);
            }
        })(marker, i));
    }
    map.fitBounds(bounds);
}

// Get current location based on the IP Address
function set_current_location() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var pos = new google.maps.LatLng(position.coords.latitude,
            position.coords.longitude);
            var myLat = position.coords.latitude;
            var myLong = position.coords.longitude;
            add_location('My location', position.coords.latitude, position.coords.longitude);
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

Can anyone help or give me a hint? I would like to add the current location to the locations array so I can keep track of how many locations I have added. Thank you so much.

任何人都可以帮助或给我一个提示吗?我想将当前位置添加到位置数组,以便我可以跟踪我添加了多少个位置。太感谢了。

回答by Anto Jurkovi?

If you just move set_markers()to the end of successcallback of getCurrentPosition()and user refuse to share his location, you won't get the map but just gray area. There is no centerset for your map which is required property. Better to define it like:

如果你只是移动set_markers()success回调的末尾getCurrentPosition()并且用户拒绝分享他的位置,你将不会得到地图而只是灰色区域。center您的地图没有设置这是必需的属性。最好将其定义为:

var myOptions = {
    zoom: 10,
    center: new google.maps.LatLng(37.339386, -121.894955),
    mapTypeControl: true,
    navigationControl: true,
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
...

Additionally, you can also call set_markers()at the end of errorcallback of getCurrentPosition(), so in case that user refuse sharing of his location, you can show available locations:

此外,您还可以set_markers()在 的error回调结束时调用getCurrentPosition(),因此如果用户拒绝共享他的位置,您可以显示可用位置:

// Get current location based on the IP Address
function set_current_location() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            /*
            var pos = new google.maps.LatLng(position.coords.latitude,
                                             position.coords.longitude);
            var myLat = position.coords.latitude;
            var myLong = position.coords.longitude;
            */
            add_location('My location', 
                        position.coords.latitude, 
                        position.coords.longitude);

            set_markers(new google.maps.LatLngBounds(), map);
        }, function error(err) {
            console.log('error: ' + err.message);
            set_markers(new google.maps.LatLngBounds(), map);            
        });
    } else {
        alert("Geolocation is not supported by this browser.");
    }
}

See example at jsbin

请参阅jsbin 中的示例