2015-10-27 4 views
1

Я пытаюсь использовать API геокодирования Google Maps в javascript. У меня есть следующий код:Google maps geocoding не возвращает местоположение

var geocoder = new google.maps.Geocoder(); 

function geocodeAddress() { 
    var address = document.getElementById("address").value; 
    geocoder.geocode({"address": address}, function(results, status) { 
    if (status === google.maps.GeocoderStatus.OK) { 
     alert(JSON.stringify(results[0].geometry)) 
    } else { 
     alert("Geocode was not successful for the following reason: " + status); 
    } 
    }); 
} 

Результат, который я получил за правильный Адрес:

{"location":{},"location_type":"ROOFTOP","viewport":{"O":{"O":52.2080810197085,"j":52.2107789802915},"j":{"j":21.018444019708568,"O":21.02114198029153}}} 

Как вы можете видеть, что это не имеет местоположение правильно установить. Любое предложение, что здесь не так?

+0

Что вы собираетесь использовать координаты для? Вы можете получить их из объекта google.maps.LatLng, используя документированные методы '.lat()' и '.lng()'. – geocodezip

ответ

2

Location свойство имеет google.maps.LatLng тип объекта, который, в свою очередь, требует явного преобразования для печати Lat/значений LNG, например:

var sval = results[0].geometry.location.toString(); 

Или вы могли бы получить доступ к LAT/LNG значения, используя соответствующие функции:

var lat = results[0].geometry.location.lat(); 
var lng = results[0].geometry.location.lng(); 

для того, чтобы напечатать строковое представление Location собственности можно заменить:

alert(JSON.stringify(results[0].geometry)); 

с

alert(JSON.stringify(results[0].geometry,convertLatLngValue,4)); 

где

function convertLatLngValue(key,value) 
{ 
    if (key=="lat" || key=="lng") { 
     return value(); 
    }  
    else 
     return value; 
} 

Живой пример

var geocoder; 
 
var map; 
 
function initialize() { 
 
    geocoder = new google.maps.Geocoder(); 
 
    var latlng = new google.maps.LatLng(-34.397, 150.644); 
 
    var mapOptions = { 
 
     zoom: 8, 
 
     center: latlng 
 
    } 
 
    map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); 
 
} 
 

 
function codeAddress() { 
 
    var address = document.getElementById('address').value; 
 
    geocoder.geocode({ 'address': address }, function (results, status) { 
 
     if (status == google.maps.GeocoderStatus.OK) { 
 
      var json = JSON.stringify(results[0].geometry,convertLatLngValue,4); 
 
      document.getElementById('output').innerHTML = json; 
 
      map.setCenter(results[0].geometry.location); 
 
      var marker = new google.maps.Marker({ 
 
       map: map, 
 
       position: results[0].geometry.location 
 
      }); 
 
     } else { 
 
      alert('Geocode was not successful for the following reason: ' + status); 
 
     } 
 
    }); 
 
} 
 

 

 
function convertLatLngValue(key,value) 
 
{ 
 
    if (key=="lat" || key=="lng") { 
 
     return value(); 
 
    }  
 
    else 
 
     return value; 
 
} 
 

 
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas { 
 
    height: 240px; 
 
    margin: 0px; 
 
    padding: 0px; 
 
} 
 

 
#panel { 
 
    position: absolute; 
 
    top: 5px; 
 
    left: 50%; 
 
    margin-left: -180px; 
 
    z-index: 5; 
 
    background-color: #fff; 
 
    padding: 5px; 
 
    border: 1px solid #999; 
 
}
<script src="https://maps.googleapis.com/maps/api/js"></script> 
 
<div id="panel"> 
 
     <input id="address" type="textbox" value="Sydney, NSW"> 
 
     <input type="button" value="Geocode" onclick="codeAddress()"> 
 
</div> 
 
<div id="map-canvas"></div> 
 
<pre id="output"></pre>

Смежные вопросы