[英]Getting latitude and longitude from an address and writing to a file
我對此有些麻煩。 我得到的印象是無法使用javascript。
我有一個文本文件,格式為:
Street # STREET CITY ST ZIP
全部用/ t分隔,我想將此地址轉換為緯度和經度坐標。
因此,其想法是從文本文件中讀取一行,然后將其寫入同一本地文件或整個新文件(如果這樣更容易)。 我只需要這樣做一次,只需一次將地址轉換為緯度和經度即可。 不會在應用程序中只需要我自己使用的經度和緯度列表(大約200個要轉換的地址)
我不確定是否可以在不使用Google Maps API的情況下執行此操作,但是我知道我可以通過以下方式檢索緯度和經度:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlong = results[0].geometry.location;
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
因此,我不僅不知道是否甚至有可能在瀏覽器中使用js寫入文件,而且我還知道上面的函數是異步運行的,並且可能使它混亂。
任何想法? 如果可以用另一種語言做到這一點會更容易嗎?
謝謝
假設您正在使用JQuery
geocoder.geocode( { 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latlong = results[0].geometry.location;
$.post('latlong.php', {'latitude': latlong.latitude, 'longitude': latlong.longitude}, function(res) {
if (!res.success)
{
alert('Something went wrong: '+res.error);
}
}, 'JSON');
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
現在, latlong.php
if (isset($_POST['latitude']) && isset($_POST['longitude']))
{
$coordinate = (object) $_POST;
$file = $_SERVER['DOCUMENT_ROOT'].'/myfile.txt';
$data = 'Latitude: ' . $coordinate->latitude . '\n' .
'Longitude: ' . $coordinate->longitude;
if (false !== file_put_contents($file, $data, FILE_APPEND))
{
return json_encode(array(
'success' => true
));
}
return json_encode(array(
'success' => false,
'error' => 'Unable to write to file.'
));
}
未經測試
這是我使用的代碼段。 我只參加了需要的部分,但是如果您需要,我可以提供其余的代碼。
function codeAddress(obj) {
var address = obj.parentNode.previousSibling.innerHTML;
geocoder.geocode( { 'address': address, 'partialmatch': true}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
// uncomment next line to center the map
// map.setCenter(results[0].geometry.location);
// uncomment next line if you want to place a marker
// placeMarker(results[0].geometry.location, map, results[0].formatted_address);
// save latlng and use it later
latlng = results[0].geometry.location.toString().replace("\(","").replace("\)","").replace(" ","");
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Tip:
只是讓您知道您每秒不能發送十個以上的查詢。 因此,如果您從文本文件中讀取地址,請執行暫停:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.