我正在使用带有自动填充功能的Google Maps JavaScript API。
我想为用户的当前位置添加一个选项(在Google生成的自动填充选项之前显示为第一个菜单选项):
HTML:
<input type="text" name="address" id="address" placeholder="Start: Your Location" />
<div id="map"></div>
JS:
var map;
function initMap() {
var input = document.getElementById('address');
var autocomplete = new google.maps.places.Autocomplete(input);
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
function getCurrentLocation() {
// Try HTML5 geolocation
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var location = new google.maps.LatLng(pos['lat'], pos['lng']); // turn coordinates into an object
geocoder.geocode({'latLng': location}, function (results, status) {
if(status == google.maps.GeocoderStatus.OK) {
// Add option as first option in autocomplete display
}
});
}, function() {
});
} else {
console.log('could not get your location.');
// Browser doesn't support Geolocation
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
}
以下是显示地图和自动填充功能的jsfiddle。