1

Hi I have an address field taking address from france only. I want that address to be stored with longitude and latitude in my database.. Is there a way to do that.. I'm trying several codes but none of them are working.

here is my code

<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);
    }
}
Sunny
  • 402
  • 4
  • 15
user3687828
  • 41
  • 10

3 Answers3

2
  1. Few functions were missing
  2. IDs in form were wrong

Have corrected both, please try code below:

<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);
      }
  }
  ?>

Also please do read: https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform

Anushil Nandan
  • 294
  • 2
  • 6
  • Thank you soo much #Anushil Nandan its working.. If I need to calculate distance from this address to that from a table address , I just have to work with the longitude and latitude? – user3687828 Apr 24 '17 at 06:16
  • you can use http://www.geodatasource.com/developers/php to find distance between two lat/long points. Here I am assuming that addresses stored in db have lat/long – Anushil Nandan Apr 24 '17 at 06:21
  • How to calculate distance from database – user3687828 Apr 24 '17 at 09:56
  • there is no mysql function that i know of. you can google though. please tell the use case please – Anushil Nandan Apr 24 '17 at 11:15
  • From my previous code, how do i use the following code from this url:http://tutorialswebsite.com/distance-calculator-two-places-using-google-map-api-php/ to calculate distance from two address..The input address is stored in table customer1 and i have another table shop.. how to calculate distance from these two address??? – user3687828 Apr 24 '17 at 13:56
  • can you please share your table structure – Anushil Nandan Apr 24 '17 at 14:19
  • Table customer1 {id int, address varchar(150), latitude(float), longitude(float)} Table shop { id int, name varchar(50), address varchar(100), latitude float, longitude float} – user3687828 Apr 24 '17 at 15:24
  • you can fetch latitude, longitude from both customer1 and shop. once you have both you can use http://www.geodatasource.com/developers/php to find the distance. hope this makes it clear. in case you are wondering about query here you go: select latitude,longitude from customer1 select latitude,longitude from shop – Anushil Nandan Apr 24 '17 at 15:53
  • you mean it has to be this? $result2 = mysql_query("SELECT latitude, longitude from shop") or die(mysql_error()); while($row2 = mysql_fetch_array( $result2 )) { $lon=$row2['lon']; $lat=$row2['lat']; } $result = mysql_query("SELECT latitude, longitude from customer1") or die(mysql_error()); $distance = 0; // accumulate the distance while($row = mysql_fetch_assoc( $result )) { $lon2a=$lon2; $lat2a=$lat2; $lon1=$row['lon1']; $lat1=$row['lat1']; $lon2=$row['lon2']; $lat2=$row['lat2']; – user3687828 Apr 24 '17 at 16:27
  • something like: $result2 = mysql_query("SELECT latitude, longitude from shop") or die(mysql_error()); while($row2 = mysql_fetch_array( $result2 )) { $lon=$row2['longitude']; $lat=$row2['latitude']; } $result = mysql_query("SELECT latitude, longitude from customer1") or die(mysql_error()); you see what's wrong with your query? you are using SELECT latitude, longitude from shop, so mysql will return results in latitude and longitude variables, but while looping in while you are using $lon=$row2['lon'] which does not exist and it will give error. – Anushil Nandan Apr 24 '17 at 16:37
  • i have corrected it but it gives me errors : undefined index, variable and cannot declare distance(), I want to get the closest address but it gives me some numbers – user3687828 Apr 24 '17 at 16:55
2

Get all addresses from databases and compare it with current latitude and longitude which you got from your form.

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' => array('address_id_1','address abcd','55.645645','-42.5323'), where 55.645645 is latitude and -42.5323 is longtitude. do not swap these else result will be wrong

seems like you are stuck on this, try this and also, do share what you are trying.

Anushil Nandan
  • 294
  • 2
  • 6
1

Sir, you need get info from here http://maps.googleapis.com/maps/api/geocode/json?address=Paris. I use 'address' instead of 'input'.

If you work only with Paris addresses, you need to do like this http://maps.googleapis.com/maps/api/geocode/json?address=Marais,Paris

aslantorret
  • 273
  • 4
  • 10