我遇到了一些麻烦。我的印象是使用 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.'
));
}
未经测试
关于javascript - 从地址获取经纬度并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24747965/