以下是我的代码,我是谷歌地图和JavaScript的新手,我正试图获得“地名”和#39;通过将位置(latlng)传递给地理编码器,但它没有返回任何值。如果将placeName var设置为' somePlace'它将标题设置为“somePlace'”。但我想用返回值设置标题,即地名。
function setMap(position){
//var Karachi = {lat: 24.8978176, lng: 66.9596003}; //default city
var location = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
var mapOptions = {
center: location,
zoom: 13, //initial zoom level
mapTypeId: 'hybrid' //map type
}
//object of map
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var placeName;
//placeName = 'SomePlace';
var newLatLng = location + '';
var latlngStr = newLatLng.split(',',2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
var geocoder = new google.maps.Geocoder({'location': latlng}, function(results, status) {
if(status === 'OK'){
if(results[1]){
placeName = 'results[1].formatted_address';
}
else{
window.alert('Error in ' + status);
}
}
else{
window.alert('Geocoder failed due to ' + status);
}
});
var markerOptions = {
position: location,
map: map,
title: placeName //<-- i want place name to be here
}
//object of marker
var marker = new google.maps.Marker(markerOptions);
marker.setTitle(placeName); //<-- this is also not working
}
答案 0 :(得分:0)
只需尝试将你的lat和long传递给下面的查询字符串,你就会得到一个json数组,从那里获取你的地名。
http://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&sensor=true
答案 1 :(得分:0)
您的代码中存在语法错误。
google.maps.Geocoder
对象调用GeocoderRequest
<ul class="flex-container column">
<li class="flex-item">1</li>
<li class="flex-item">2</li>
<li class="flex-item">3</li>
<li class="flex-item">4</li>
<li class="flex-item">5</li>
</ul>
方法:geocode
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
location: location
}, function(results, status)
代码段
if (results[1]) {
placeName = results[1].formatted_address;
var markerOptions = {
position: location,
map: map,
title: placeName //<-- i want place name to be here
}
//object of marker
var marker = new google.maps.Marker(markerOptions);
function setMap(position) {
var location = {
lat: position.coords.latitude,
lng: position.coords.longitude
}
var mapOptions = {
center: location,
zoom: 13, //initial zoom level
mapTypeId: 'hybrid' //map type
}
//object of map
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var geocoder = new google.maps.Geocoder();
geocoder.geocode({
location: location
}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
placeName = results[1].formatted_address;
var markerOptions = {
position: location,
map: map,
title: placeName // set formatted_address as title of marker
}
//object of marker
var marker = new google.maps.Marker(markerOptions);
} else {
window.alert('Error in ' + status);
}
} else {
window.alert('Geocoder failed due to ' + status);
}
});
}
google.maps.event.addDomListener(window, "load", function() {
setMap({
coords: {
latitude: 37.4419,
longitude: -122.1419
}
})
});
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}