0

I have a database that stores clients and employees. The front end for that database uses very old software (coded in vb6 from the late 90s so I can't simply geocode the addresses for insertion upon entry, unless i wanna do some fancy sql work). I am building some more robust reporting software for the data. I want to include google map features in the software that shows where clients and employees live. When a roster of current employees or clients is generated, I also want it to check for new additions and then geocode their addresses into a database table so that I can reference them in later reports. I have no problem with recognizing the new entries or geocoding their locations.

The way the php script works is it checks to see if clients have latitude and longitude information populated already, and if not, get the lat/lng, and then insert it into the database. If there are several new clients/employees, i want it to loop through the result set and insert the relative information. The issue is the google api gets the lat/lng via javascript, so I can't pass that information back into the php script to store it into the database, and I don't really want to use javascript to insert it.

So i'm wondering the best way to go about this. I have been researching and testing for a couple hours now. I figured I could probably pass the variables through ajax techniques, but isn't that going to cause an issue when doing it in the middle of a loop?

Here's some sample code, and I apologize for such a drawn out question!

Javascript snippet of geocode:

function codeAddress(address) {

  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
        var newlat = results[0].geometry.location.lat();
        var newlng = results[0].geometry.location.lng();
        alert(results[0].geometry.location);


    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });

php snippet:

$address = "";
$num = 0;
//Google geocode limits requests to 10 per second, limit to 5 total requests at a time.
//If more theres more than 10 clients who have yet to be geocoded, running the database insertion code
//---should provide long enough delay to geocode again and not hit the overflow limit


while ($row = mssql_fetch_array($result) and $num < 5) {
   if ($row['lat'] == "") {
        //Create address string
        $address = $row['Address1'] . " " . $row['City'] . ", NY " . $row['Zip'];
        $address = str_replace("'", "", $address);
       //Test to show addresses without lat/lng were pulled
        echo "<script>codeAddress('" . $address . "');</script>" . $address . "<br />";
        $num = $num + 1;
        }

    }
6
  • Why do you say "so I can't pass that information back into the php script to store it into the database"? Commented Mar 7, 2015 at 22:34
  • Because my understanding is that php is run server side first, so its run prior to the javascript code which is then run after. So i can't just tell javascript to insert "this chunk of php code", and then continue with the php script. Is that not true? Commented Mar 7, 2015 at 22:38
  • That is true, but you can submit the results to a PHP script on your server and use that script to post the data to your database (as you say in your post, I don't consider it "using AJAX techniques" if you aren't using XML and you aren't returning a result to the client...). You can solve the "loop" issue by including an identifier in the data returned. Commented Mar 7, 2015 at 22:47
  • 1
    You can call the api directly in php, something like: file_get_contents("http://maps.google.com/maps/api/geocode/json?sensor=false&address=$addtress"); Commented Mar 7, 2015 at 22:48
  • As usual the answer is always simple. I definitely can pull the data simply using an http request. Thank you steve Commented Mar 7, 2015 at 22:54

1 Answer 1

1

Here is the code to convert address into geocoordinates (lat, lang):

<?php
      $Address = urlencode($Address);
      $request_url = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$Address."&sensor=true";
      $xml = simplexml_load_file($request_url) or die("url not loading");
      $status = $xml->status;
      if ($status=="OK") {
          $Lat = $xml->result->geometry->location->lat;
          $Lon = $xml->result->geometry->location->lng;
          $LatLng = "$Lat,$Lon";
      }
    ?>

You can store these Lat Lng in Database with a simple SQL query and then retrieve it back to display on the map. For that you have to display the Map. See the following code to doo that:

<!DOCTYPE html>

<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Google Maps Example</title>
        <style type="text/css">
            body { font: normal 14px Verdana; }
            h1 { font-size: 24px; }
            h2 { font-size: 18px; }
            #sidebar { float: right; width: 30%; }
            #main { padding-right: 15px; }
            .infoWindow { width: 220px; }
        </style>
        <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
        <script type="text/javascript">
        //<![CDATA[

        var map;

        // Ban Jelačić Square - Center of Zagreb, Croatia
        var center = new google.maps.LatLng(45.812897, 15.97706);

        function init() {

            var mapOptions = {
                zoom: 13,
                center: center,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

            var marker = new google.maps.Marker({
                map: map, 
                position: center,
            });
        }
        //]]>
        </script>
    </head>
    <body onload="init();">

        <h1>Places to check out in Zagreb</h1>

        <section id="sidebar">
            <div id="directions_panel"></div>
        </section>

        <section id="main">
            <div id="map_canvas" style="width: 70%; height: 500px;"></div>
        </section>

    </body>
</html>

To get the data from the Database:

<?php

$server     = 'localhost';
$username   = 'root';
$password   = 'YOUR_PASSWORD';
$database   = 'YOUR_DATABASE';

$dsn        = "mysql:host=$server;dbname=$database";

Now Create your own file that will return the actual data.

<?php

    require 'config.php';

    try {

        $db = new PDO($dsn, $username, $password);
        $db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );

        $sth = $db->query("SELECT * FROM locations");
        $locations = $sth->fetchAll();

        echo json_encode( $locations );

    } catch (Exception $e) {
        echo $e->getMessage();
    }

To display locations on the map you have to make AJAX requests:

function makeRequest(url, callback) {
    var request;
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
    } else {
        request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
    }
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            callback(request);
        }
    }
    request.open("GET", url, true);
    request.send();
}

Define your init() function which will have the JSON response:

var map;

// Ban Jelačić Square - City Center
var center = new google.maps.LatLng(45.812897, 15.97706);

var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();

function init() {

    var mapOptions = {
      zoom: 13,
      center: center,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    makeRequest('get_locations.php', function(data) {

        var data = JSON.parse(data.responseText);

        for (var i = 0; i < data.length; i++) {
            displayLocation(data[i]);
        }
    });
}

Finally you need to display the locations on the map, you can add a info window like this:

function displayLocation(location) {

    var content =   '<div class="infoWindow"><strong>'  + location.name + '</strong>'
                    + '<br/>'     + location.address
                    + '<br/>'     + location.description + '</div>';

    if (parseInt(location.lat) == 0) {
        geocoder.geocode( { 'address': location.address }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {

                var marker = new google.maps.Marker({
                    map: map, 
                    position: results[0].geometry.location,
                    title: location.name
                });

                google.maps.event.addListener(marker, 'click', function() {
                    infowindow.setContent(content);
                    infowindow.open(map,marker);
                });
            }
        });
    } else {
        var position = new google.maps.LatLng(parseFloat(location.lat), parseFloat(location.lon));
        var marker = new google.maps.Marker({
            map: map, 
            position: position,
            title: location.name
        });

        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(content);
            infowindow.open(map,marker);
        });
    }
}

Hope this Helps!!

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much AniV. Thanks to Steve's suggestion I was able to adjust my code to just pull the lat/lng through php as a json object, but this is a fantastic reference for anyone as it shows the entire picture, so kudos to you sir.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.