我一直在尝试将GoogleMaps API为开发人员提供的两个功能(地点搜索和地理位置(放在一起
由于我对javascript不是很熟悉,所以我不确定我所犯的错误是什么。到目前为止,地点搜索是完全有效的(具有预定位置(,但地理位置(应用用户的位置覆盖预定位置(则不然。
在这里你可以看看我的代码。
<!DOCTYPE html>
<html>
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
#map {
height: 580px;
width: 680px;
border: 10px solid darkred;
padding: 5px;
margin: 25px;
}
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
// 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;
function initMap() {
var pyrmont = {lat:43.364490, lng:-8.407406};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow({map:map});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 2000,
type: ['gym']
}, callback);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} 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.');
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
</script>
</head>
<body>
<header>
<h1>Encuentra tu gimnasio más próximo</h1>
</header>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=***MY_KEY***&libraries=places,geometry&callback=initMap" async defer></script>
</body>
</html>
任何帮助将不胜感激。
infoWindow
变量的大小写似乎有错误。
它是这样声明的:
var infowindow;
但是在回调中navigator.geolocation.getCurrentPosition
使用了不同的大小写:
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
此错误应显示在浏览器的开发工具控制台中。