我正在做一个项目,定位用户位置附近的咖啡店(通过浏览器检索)。我使用Google Maps API来进行地理位置定位。
我的想法是通过地理位置来定位用户的位置,然后检索他们附近的咖啡店。我似乎想不出如何添加咖啡店或自动搜索,并在浏览器检索到位置后在地图上显示用户附近的咖啡店。
硬编码的位置似乎并不是解决办法,但我希望从更有经验的程序员那里得到一些关于如何做到这一点的建议。
目前,地图的代码来自Google Maps文档,因为它提供了我所需要的除搜索以外的功能。
我把它粘贴在下面。
function mapFunc() {
// referenced from google maps api documentation
var map;
var infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 15
});
infoWindow = new google.maps.InfoWindow;
//HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('You are here!');
infoWindow.open(map);
map.setCenter(pos);
}, function () {
handleLocationError(true, infoWindow, map.getCenter());
search();
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
//get coffee shops nearby??
}
mapFunc();
你需要使用Google Map api中的地方库。
在下面的标签中包含它
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places"></script>
然后使用类似下面的示例代码。
var map;
var service;
var infowindow;
function initialize() {
//replace the lat long with results from your geocoding function
var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: '500', //radius in metres
type: ['coffee shops']
};
service = new google.maps.places.PlacesService(map);
service.nearbySearch(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
详细内容见 https:/developers.google.commapsdocumentationjavascriptplaces#place_search_requests。