我正在尝试根据用户位置显示信息。所以,在这里我想根据他的位置向该用户显示五个最近的位置(名称)。
我怎样才能使用JavaScript。帮助我。
答案 0 :(得分:1)
Javascript使您能够获得用户的地理位置。这就是全部。
如果您想在地理位置附近找到一些地方,则需要使用任何地理服务API,例如Google地图或yandex地图等。
我建议你看一下这个回购:https://github.com/googlemaps/js-store-locator
此外,您可以在此处查看所需内容的示例: https://googlemaps.github.io/js-store-locator/examples/places.html
答案 1 :(得分:0)
您需要使用Google Maps Places API:
以下是代码和工作小提琴DEMO:
HTML:
<div id="map"></div>
<div id="places"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places,geometry&callback=initMap" async defer></script>
CSS:
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: calc(100% - 200px);
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#places {
background-color: #fff;
height: 200px;
overflow: auto;
padding: 10px 15px;
}
使用Javascript:
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
var currentLat = -33.867;
var currentLng = 151.195;
var list = document.getElementById('places');
function initMap() {
var currentPoint = {lat: currentLat, lng: currentLng};
map = new google.maps.Map(document.getElementById('map'), {
center: currentPoint,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: currentPoint,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
var nearestPlaces = getnearestPlaces(results, 5);
for (var i = 0; i < nearestPlaces.length; i++) {
listPlaces(nearestPlaces[i]);
}
}
}
function getnearestPlaces(places, numberOfResults) {
var closest = [];
for (var i = 0; i < places.length; i++) {
var fromPoint = new google.maps.LatLng(currentLat, currentLng);
var toPoint = new google.maps.LatLng(places[i].geometry.location.lat, places[i].geometry.location.lng);
places[i].distance = google.maps.geometry.spherical.computeDistanceBetween(fromPoint, toPoint);
closest.push(places[i]);
}
closest.sort(sortByDist);
return closest.splice(0,numberOfResults);
}
function sortByDist(a, b) {
return (a.distance - b.distance)
}
function listPlaces(place) {
console.log(place);
list.innerHTML += '<p>' + place.name + '</p>';
}