我有 javascript 将街道地址转换为坐标。但我想要的是当用户在输入字段中输入地址时,javascript 将其转换为 lat 和 lng 并将结果放在 ap div 中,例如在输入字段下方。
我的JS代码是
var latitude;
var longitude;
/*
* Get the json file from Google Geo
*/
function Convert_LatLng_To_Address(address, callback) {
url = "http://maps.googleapis.com/maps/api/geocode/json?address=" + address + "&sensor=false";
jQuery.getJSON(url, function (json) {
Create_Address(json, callback);
});
}
/*
* Create an address out of the json
*/
function Create_Address(json, callback) {
if (!check_status(json)) // If the json file's status is not ok, then return
return 0;
latitude = json["results"][0]["geometry"]["location"]["lat"];
longitude = json["results"][0]["geometry"]["location"]["lng"];
callback();
}
/*
* Check if the json data from Google Geo is valid
*/
function check_status(json) {
if (json["status"] == "OK") return true;
return false;
}
<body>
Address:
<input type="text" id="address-input">
City:
<input type="text" id="city-input">
Country:
<input type="text" id="country-input">
Postcode:
<input type="text" id="address4">
<input type="submit" id="submit" value="generate" onClick="AlertLatLng()">
<p id="result"></p>
<script>
var street_address = document.getElementById('address-input').value,
city = document.getElementById('city-input').value,
country = document.getElementById('country-input').value,
postcode = document.getElementById('postcode-input').value;
var address = street_address + ' ' + city + ' ' + country + ', ' + postcode;
// AlertLatLng is a callback function which will be executed after converting address to coordinates
Convert_LatLng_To_Address(address, AlertLatLng);
/*
* Alert Latitude & Longitude
*/
function AlertLatLng() {
var result = "The latitude is " + latitude + " and longitude is " + longitude;
document.getElementById('result').innerHTML=result;
}
</scrip>
</body>
提前致谢 :)