这个我有一些麻烦。我得到的印象这是不可能使用javascript。
我有一个格式为:
的文本文件Street # STREET CITY ST ZIP
全部用/t分隔,我想把这个地址转换成经纬度坐标。
所以这个想法是从文本文件中读取一行,然后写入同一个本地文件或写入一个完整的新文件,如果这更容易的话。我只需要这样做一次,只需一次将地址转换为纬度和经度。不会在应用程序中只需要我自己使用的纬度和经度列表(大约200个地址要转换)
我不确定是否有这样做,而不使用谷歌地图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:
只是想让你知道你每秒不能发送超过10个查询。所以,如果你从一个文本文件中读取地址,实现一个pause:)