Google ジオコーダ API V3 を使用して、ユーザーが指定した住所に基づいて地図上に位置をプロットしようとしています。コードは以下のとおりです。
直接リクエストを行うと (たとえば、http://maps.googleapis.com/maps/api/geocode/json?address=peterborough&sensor=falseに)、期待どおりの応答が得られます。ただし、以下のコードを使用して同じリクエストを行うと、 getLatLong関数が終了した後、 midpoint変数は常に未定義です。
私は間違って何をしていますか?
function loadFromSearch(address)
{
midpoint = getLatLong(address);
mapCentre = midpoint;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
function getLatLong(address)
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,
function (data){
if (data.status == "OK")
{
result = data.results[0].geometry.location;
}
});
return result;
}
================================================== ================================
回答を踏まえて、コードを次のように更新しました。Firebug でブレークポイントを設定すると、結果はまだ得られません。結果 = data.results[0].geometry.location; 当たることはありません。
function loadFromSearch(address)
{
midpoint = getLatLong(address, loadWithMidpoint);
}
function getLatLong(address, callback)
{
var result;
var url = 'http://maps.googleapis.com/maps/api/geocode/json?address=' + encodeURIComponent(address) + '&sensor=false'
$.getJSON(url,{},
function (data) {
if (data.status == "OK")
{
result = data.results[0].geometry.location;
callback(result);
}
});
}
function loadWithMidpoint(centre)
{
mapCentre = centre;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}
================================================== ===========================
私はそれを持ってます!動作する最終的なコードは次のようになります。
function loadFromSearch(coordinates, address)
{
midpoint = getLatLong(address, latLongCallback);
}
function getLatLong(address, callback)
{
var geocoder = new google.maps.Geocoder();
var result = "";
geocoder.geocode({ 'address': address, 'region': 'uk' }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK)
{
result = results[0].geometry.location;
latLongCallback(result);
}
else
{
result = "Unable to find address: " + status;
}
});
return result;
}
function latLongCallback(result)
{
mapCentre = result;
map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
...
}