javascript - 从地址获取经纬度并写入文件

标签 javascript php html google-maps file-io

我遇到了一些麻烦。我的印象是使用 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/

相关文章:

javascript - 使用 jquery flot 绘制 json 数组

javascript - 单击主自定义复选框打开一个复选框组

php - Laravel:在 PDO 对象上指定了不受支持的属性。 Ubuntu 上的 MSSQL

php - 混淆组和带有 php 的子句

javascript - 如何在 Microsoft edge 中获取选中的单选按钮的值?

javascript - 在 Javascript 中使用内部数组构建 JSON 对象

php - Codeigniter - 检测浏览器的最佳方法

javascript - 使用索引在不同的 div 上添加 Active 类

javascript - .checked 和 .disable 在 javascript 中不能一起工作

javascript - 滚动时CSS更改导航栏背景颜色