如何从输入地址获取纬度和经度

Posted

技术标签:

【中文标题】如何从输入地址获取纬度和经度【英文标题】:How to get latitude and longitude from an input address 【发布时间】:2017-04-24 04:43:38 【问题描述】:

您好,我有一个地址字段,仅从法国获取地址。 我希望将该地址与经度和纬度一起存储在我的数据库中。有没有办法做到这一点。我正在尝试几个代码,但没有一个有效。

这是我的代码

<form id="contact" action="send.php" method="post"><br> 
    <h2>Formulaire de contact</h2>
    <div id="locationField" required>
        <input id="autocomplete" placeholder="Adresse"
               onFocus="geolocate()" type="text" name="address" required="required"></input>
    </div><br>
    <input type="hidden" name="latitude" id="at" placeholder="Latitude" class="form-control" required="required"/>
    <input type="hidden" name="longitude" id="lng" placeholder="Longitude" class="form-control" required="required"/>
    <input type="submit" name="submit" value="submit" class="button"/>

    <script>
        function initAutocomplete() 
            autocomplete = new
                    google.maps.places.Autocomplete(
                            /** @type !htmlInputElement  

                             */(document.getElementById('autocomplete')),
                            types: ['geocode'], componentRestrictions: country: 'fr');

            autocomplete.addListener('place_changed', fillInAddress);
        

        document.getElementById('latitude').value = place.geometry.location.lat();
        document.getElementById('longitude').value = place.geometry.location.lng();
    </script>

    <script src="https://maps.googleapis.com/maps/api/js?input=Paris&types=geocode&key=xxxxxxxxxxxxxxxxxxxxxx&libraries=places&callback=initAutocomplete"
    async defer></script>
</form>

<?php
if (isset($_POST["submit"])) 
    $servername = "localhost";
    $username = "root";
    $password = "";
    $dbname = "web_contact";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);

    if ($conn->connect_error) 
        die("Connection failed: " . $conn->connect_error);
    

    $sql = "INSERT INTO customer1(address,latitude,longitude) 

  values('" . $_POST["address"] . "','" . $_POST["latitude"] . "','" . $_POST["longitude"] . "')";

    if (mysqli_query($conn, $sql)) 
        echo "New record created successfully";
     else 
        echo "Error: " . $sql . "" . mysqli_error($conn);
    

【问题讨论】:

请修正代码格式 并删除私有 API 密钥 请看这个链接***.com/questions/3807963/… 【参考方案1】:

从数据库中获取所有地址,并将其与您从表单中获取的当前纬度和经度进行比较。

function distance($a, $b)

    list($lat1, $lon1) = $a;
    list($lat2, $lon2) = $b;

    $theta = $lon1 - $lon2;
    $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +  cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
    $dist = acos($dist);
    $dist = rad2deg($dist);
    $miles = $dist * 60 * 1.1515;
    return $miles;


$myAddress = array(49.648881, -103.575312);

$allAddresses = array(
    '0' => array('address_id_1','address abcd','55.645645','-42.5323'),
    '1' => array('address_id_2','second address abcd','100.645645','-402.5323')
);

$distances = array_map(function($item) use($myAddress) 
    $a = array_slice($item, -2);
    return distance($a, $myAddress);
, $allAddresses);

asort($distances);

echo 'Closest item is: ', print_r($allAddresses[key($distances)]);

'0' =&gt; array('address_id_1','address abcd','55.645645','-42.5323'), 其中 55.645645 是 latitude 而 -42.5323 是 longtitude。不要交换这些否则结果将是错误的

似乎你被困住了,试试这个,也分享你正在尝试的东西。

【讨论】:

我需要声明那个函数?【参考方案2】:
    缺少一些功能 表格中的 ID 错误

已更正两者,请尝试以下代码:

<form id="contact" action="send.php" method="post"><br>
      <h2>Formulaire de contact</h2>
      <div id="locationField" required>
          <input id="autocomplete" placeholder="Adresse"
                 onFocus="geolocate()" type="text" name="address" required="required"></input>
      </div><br>
      <input name="latitude" id="latitude" placeholder="Latitude" class="form-control" required="required"/>
      <input name="longitude" id="longitude" placeholder="Longitude" class="form-control" required="required"/>
      <input type="submit" name="submit" value="submit" class="button"/>

      <script>

            // Bias the autocomplete object to the user's geographical location,
        // as supplied by the browser's 'navigator.geolocation' object.
        function geolocate() 
          if (navigator.geolocation) 
            navigator.geolocation.getCurrentPosition(function(position) 
              var geolocation = 
                lat: position.coords.latitude,
                lng: position.coords.longitude
              ;
              var circle = new google.maps.Circle(
                center: geolocation,
                radius: position.coords.accuracy
              );
              autocomplete.setBounds(circle.getBounds());
            );
          
        
          function initAutocomplete() 
              autocomplete = new
                      google.maps.places.Autocomplete(
                              /** @type !HTMLInputElement

                               */(document.getElementById('autocomplete')),
                              types: ['geocode'], componentRestrictions: country: 'fr');

              autocomplete.addListener('place_changed', fillInAddress);
          
          function fillInAddress() 
            var place = autocomplete.getPlace();
            console.log(place);
          document.getElementById('latitude').value = place.geometry.location.lat();
          document.getElementById('longitude').value = place.geometry.location.lng();
        
      </script>

      <script src="https://maps.googleapis.com/maps/api/js?input=Paris&types=geocode&key=AIzaSyBJCSjFGcsFkG5Zy7k3Ph6ArHv6EoWSxpk&libraries=places&callback=initAutocomplete"
      async defer></script>
  </form>

  <?php
  if (isset($_POST["submit"])) 
      $servername = "localhost";
      $username = "root";
      $password = "";
      $dbname = "web_contact";

      // Create connection
      $conn = new mysqli($servername, $username, $password, $dbname);

      if ($conn->connect_error) 
          die("Connection failed: " . $conn->connect_error);
      

      $sql = "INSERT INTO customer1(address,latitude,longitude)

    values('" . $_POST["address"] . "','" . $_POST["latitude"] . "','" . $_POST["longitude"] . "')";

      if (mysqli_query($conn, $sql)) 
          echo "New record created successfully";
       else 
          echo "Error: " . $sql . "" . mysqli_error($conn);
      
  
  ?>

也请阅读:https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

【讨论】:

非常感谢#Anushil Nandan 它的工作。如果我需要计算从这个地址到表地址的距离,我只需要使用经度和纬度? 您可以使用geodatasource.com/developers/php 查找两个纬度/经度点之间的距离。这里我假设存储在 db 中的地址有 lat/long 如何计算与数据库的距离 没有我知道的 mysql 函数。你可以谷歌虽然。请告诉用例请 从我之前的代码中,我如何使用此 url 中的以下代码:tutorialswebsite.com/… 来计算与两个地址的距离。输入地址存储在表 customer1 中,我有另一个表店。 . 如何计算到这两个地址的距离???【参考方案3】:

先生,您需要从这里http://maps.googleapis.com/maps/api/geocode/json?address=Paris 获取信息。我使用“地址”而不是“输入”。

如果您只使用巴黎地址,则需要这样做 http://maps.googleapis.com/maps/api/geocode/json?address=Marais,Paris

【讨论】:

以上是关于如何从输入地址获取纬度和经度的主要内容,如果未能解决你的问题,请参考以下文章

如何从android中的纬度和经度获取完整的地址? [复制]

如何获取整个地址的经纬度?

如何从 windows phone 中的纬度和经度值获取地址?

如何从C#中的地址获取纬度和经度

如何使用 ionic 中的 java 脚本从谷歌地图中的地址获取经度和纬度

如何在 Windows 上使用 Qt c++ 从一个地理地址获取纬度/经度?