我获得了Google Places API代码,并且我还添加了代码, 我已经有了像纬度和经度这样的当前位置,但我不知道如何将变量如lat1和lng1传递给Google API。
<!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: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript">
function initGeolocation()
{
if( navigator.geolocation )
{
navigator.geolocation.getCurrentPosition( success, fail );
}
else
{
alert("Sorry, your browser does not support geolocation services.");
}
}
function success(position)
{
var lng1= position.coords.longitude;
var lat1= position.coords.latitude;
}
function fail()
{
// Could not obtain location
}
</script>
<script>
var map;
var infowindow;
function initMap() {
var pyrmont = {lat:lat1, lng:lng1};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
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 onLoad="initGeolocation();">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDFvTqvbyut42xc-nF2kToD0Mzwh-_nVvw&libraries=places&callback=initMap" async defer></script>
</body>
</html>
我已经声明了变量但是当我通过它时什么也没有显示...... 提前谢谢! 如果有人知道如何将当前纬度和经度变量传递给谷歌API代码,请在此处留下答案!
答案 0 :(得分:0)
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
function showError(error) {
switch(error.code) {
case error.PERMISSION_DENIED:
x.innerHTML = "User denied the request for Geolocation."
break;
case error.POSITION_UNAVAILABLE:
x.innerHTML = "Location information is unavailable."
break;
case error.TIMEOUT:
x.innerHTML = "The request to get user location timed out."
break;
case error.UNKNOWN_ERROR:
x.innerHTML = "An unknown error occurred."
break;
}
}
</script>