2017-10-05 14 views
-1

人々が場所を変更できる機能を実装したいと考えています。そのために私はGoogleの場所APIを使用したい。今私が欲しいのは検索ボックスです。誰かが町/場所を入力すると、Googleの場所を検索して結果を出します。場所が選ばれると、それは私にその場所の緯度と経度を与えるでしょう。地図なしでそれは可能ですか?地図のないGoogleの場所の検索ボックスですか?

おかげ

答えて

5

あなたは、正確なアドレスを取得するためにGoogleマッププレイスオートコンプリートを使用することができ、その後、あなたは成功しますが、緯度とLNGを得るためにそれをジオコーディングすることができますアドレスを取得した後。このよう

function codeAddress(address) { 
    geocoder.geocode({ 'address': address}, function(results, status) { 
     if (status == 'OK') { 
     alert(results[0].geometry.location); // This is the lat and lng 
     } else { 
     alert('Geocode was not successful for the following reason: ' + status); 
     } 
    }); 
} 

チェックこの作業例:https://jsbin.com/pejagub/edit?html,js,output

私もここに挿入jsbin包みコードスニペットは

var placeSearch, autocomplete, geocoder; 
 

 
function initAutocomplete() { 
 
    geocoder = new google.maps.Geocoder(); 
 
    autocomplete = new google.maps.places.Autocomplete(
 
    (document.getElementById('autocomplete')), { 
 
     types: ['geocode'] 
 
    }); 
 

 
    autocomplete.addListener('place_changed', fillInAddress); 
 
} 
 

 
function codeAddress(address) { 
 
    geocoder.geocode({ 
 
    'address': address 
 
    }, function(results, status) { 
 
    if (status == 'OK') { 
 
     // This is the lat and lng results[0].geometry.location 
 
     alert(results[0].geometry.location); 
 
    } else { 
 
     alert('Geocode was not successful for the following reason: ' + status); 
 
    } 
 
    }); 
 
} 
 

 
function fillInAddress() { 
 
    var place = autocomplete.getPlace(); 
 

 
    codeAddress(document.getElementById('autocomplete').value); 
 
}
#autocomplete { 
 
    width: 100%; 
 
}
<!DOCTYPE html> 
 
<html> 
 

 
<head> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 

 
<body> 
 
    <div id="locationField"> 
 
    <input id="autocomplete" placeholder="Enter your address" type="text" /> 
 
    </div> 
 
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKQX3cyZ7pVKmBwE8wiowivW9qH62AVk8&libraries=places&callback=initAutocomplete" async defer></script> 
 
</body> 
 

 
</html>

が動作していません
関連する問題