我正在使用以下代码从自动填充对象的places_changed
事件中获取照片参考。
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
var ref = place.reference;
var url = "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference="+ref;
});
那么我将如何向url
发出HTTP请求。使用$.getJSON()
会导致CORS问题。还有其他办法可以解决这个问题吗?
答案 0 :(得分:0)
<p id="demo">Click the button to get your position.</p>
<button onclick="getLocation()">Try It</button>
<div id="mapholder"></div>
<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) {
var latlon = position.coords.latitude + "," + position.coords.longitude;
var img_url = "http://maps.googleapis.com/maps/api/staticmap?center="
+latlon+"&zoom=14&size=400x300&sensor=false";
document.getElementById("mapholder").innerHTML = "<img src='"+img_url+"'>";
}
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>
试试这段代码......
答案 1 :(得分:0)
创建<img/>
- 元素,将src属性设置为url
并将其放在您想要的位置https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
与配额问题相关:您正在通过网络服务(https://developers.google.com/places/webservice/photos)加载照片,此处需要密钥。
当您使用地图的地点库时,Javascript-API会通过getUrl()
检索照片的网址,您可以在没有密钥的情况下加载照片:
function init() {
var image = new Image(),
input = document.getElementsByTagName('input')[0];
var autocomplete = new google.maps.places.Autocomplete(input);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (place.photos && place.photos.length) {
input.style.background = '#fff';
image.src = place.photos[0].getUrl({
maxwidth: 200,
maxHeight: 150
});
document.body.appendChild(image);
} else {
input.style.background = 'tomato';
if (image.parentNode) {
image.parentNode.removeChild(image)
}
}
});
}
google.maps.event.addDomListener(window, 'load', init);
html,
body {
margin: 0;
padding: 0;
text-align: center;
}
<script src="http://maps.googleapis.com/maps/api/js?v=3&libraries=places"></script>
<input/>
<br/>