【发布时间】:2016-03-28 10:23:49
【问题描述】:
我知道很多线程都在讨论这个问题,但我的代码仍然不起作用。
我正在使用谷歌地方搜索框 API。
我的代码:
function initMap(){
var map = new google.maps.Map(document.getElementById('peta'), {
center: {lat: -34.397, lng: 150.644},
zoom: 16
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try 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('Your Location.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
var input = document.getElementById('alamat');
var searchBox = new google.maps.places.SearchBox(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
document.getElementById('x').innerHTML(places.geometry.location.lat());
});
}
链接脚本:
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&libraries=places"></script>
html:
<div id="peta" style="width:500px;height:380px;"></div>
<input type="text" id="x" readonly="readonly" name="x">
我在我的文本框中输入了document.getElementById,但它仍然没有显示纬度。我应该把这段代码放在哪里?
在其他线程中:
var location= places.geometry.location;
var lat = location.lat();
但它不起作用。我该如何解决这个问题?
【问题讨论】:
-
我在发布的代码中收到一个 javascript 错误:
Uncaught ReferenceError: map is not defined。请提供一个Minimal, Complete, Tested and Readable example 来证明您的问题。和Uncaught TypeError: Cannot read property 'value' of null在这一行var input = document.getElementById('alamat');(不在提供的 HTML 中)。 -
ok。抱歉。我已经更新了描述。
标签: javascript php google-maps