Forums

Geocode address on form submit

GreyHead 18 Jul, 2012
Hi Mark,

I had a search around last night but couldn't find anything that would tell me the differences between V2 and v3 of the API or what needed to be done to upgrade from one to the other. So you know of anything like that?

Bob
marklandry 18 Jul, 2012
A bit more than yesterday.

There's no longer a key, so to load:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

Geocoding's now pretty simple:
function codeAddress() {
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        map.setCenter(results[0].geometry.location);
        var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  }


Is it kosher to ask for a .bak of the form you created in the link above? If not, no sweat, I repeated your steps and couldn't get it to work, wanted to play around with it for a bit if possible.

Here's my working map if anyone else is trying to do the same, although I can't get it to center on user input... not ready to integrate into CF...

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Tantomedia AON Map</title>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
    <script type="text/javascript">
    //<![CDATA[

    var customIcons = {
      restaurant: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
        //shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      },
      bar: {
        icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
        //shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
      }
    };
    var map;
    var geocoder;
    function load() {
      var latlng = new google.maps.LatLng(39.824476,-105.080261);
      var map = new google.maps.Map(document.getElementById("map_canvas"), {
        center: latlng,
        zoom: 13,
        mapTypeId: 'roadmap'
      });

      geocoder = new google.maps.Geocoder();
      
      var infoWindow = new google.maps.InfoWindow;
      google.maps.event.addListener(map, 'idle', showMarkers);
     
       function showMarkers(){
        var bounds = map.getBounds(); 
           var ne = bounds.getNorthEast();
           var sw = bounds.getSouthWest();
           var neLong = ne.lng();
           var neLat = ne.lat();
           var swLong = sw.lng();
           var swLat = sw.lat();
           //var neLong = -105.011;
           //var neLat = 39.864;
           //var swLong = -105.1489;
           //var swLat = 39.784;
           //alert("NE LAT = "+neLat + "\nNE LONG = "+neLong + "\nSW LAT = "+swLat + "\nSW LONG = "+swLong);
           //tanto ='"'+'phpsqlajax_genxml3.php?swLat='+swLat+'&swLong='+swLong+'&neLat='+neLat+'&neLong='+neLong+'"';
           tanto ="phpsqlajax_genxml3.php?swLat="+swLat+"&swLong="+swLong+"&neLat="+neLat+"&neLong="+neLong;
           //tanto = "phpsqlajax_genxml3.php";
           //alert(tanto);
      // Change this depending on the name of your PHP file
      downloadUrl(tanto, function(data) {
      //downloadUrl("phpsqlajax_genxml3.php", function(data) {
        var xml = data.responseXML;
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
          var name = markers[i].getAttribute("name");
          var address = markers[i].getAttribute("address");
          var type = markers[i].getAttribute("type");
          var point = new google.maps.LatLng(
              parseFloat(markers[i].getAttribute("lat")),
              parseFloat(markers[i].getAttribute("lng")));
          var html = "<b>" + name + "</b> <br/>" + address;
          var icon = customIcons[type] || {};
          var marker = new google.maps.Marker({
            map: map,
            position: point,
            icon: icon.icon,
            shadow: icon.shadow
          });

          bindInfoWindow(marker, map, infoWindow, html);
        }
      });
     }
    }
  

    function bindInfoWindow(marker, map, infoWindow, html) {
      google.maps.event.addListener(marker, 'click', function() {
        infoWindow.setContent(html);
        infoWindow.open(map, marker);
      });
    }

    function downloadUrl(url, callback) {
      var request = window.ActiveXObject ?
          new ActiveXObject('Microsoft.XMLHTTP') :
          new XMLHttpRequest;

      request.onreadystatechange = function() {
        if (request.readyState == 4) {
          request.onreadystatechange = doNothing;
          callback(request, request.status);
        }
      };

      request.open('GET', url, true);
      request.send(null);
    }

    function doNothing() {}

function codeAddress() {
    var loc=[];
    var map;
    var address = document.getElementById("address").value;

    // next line creates asynchronous request
    geocoder.geocode( { 'address': address}, function(results, status) {
      // and this is function which processes response
      if (status == google.maps.GeocoderStatus.OK) {
        loc[0]=results[0].geometry.location.lat();
        loc[1]=results[0].geometry.location.lng();
        var middle = results[0].geometry.location;
        var addressbox = document.getElementById('address');  
        var latbox = document.getElementById('lat');  
        var longbox = document.getElementById('long'); 
        var testbox = document.getElementById('testbox');
        latbox.value = loc[0];
        longbox.value = loc[1];
        testbox.value = results[0].geometry.location;
        map.setCenter(middle);
        var marker = new google.maps.Marker({
            map: map, 
            position: results[0].geometry.location
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    
  }



    //]]>

  </script>



  </head>

<body onload="load()">

    <div id="map_canvas" style="width: 800px; height: 600px"></div>

    <div>

<input id="address" type="textbox" value="1135 Eudora"/>
<input id = "lat" type="textbox"/>
<input id = "long" type="textbox"/>
<input id = "testbox" type="textbox"/>
<input type="Submit" value="Submit" onclick="codeAddress()" />


  </div>

  </body>

</html>
GreyHead 18 Jul, 2012
Hi Mark,

Just a quick reply before I pack up for the night. Look at my post in the thread you linked to you'll see that I used a Custom Code action to load the Google script files and a Load JS action to load the customised script (though that could have gone in a file too).

Bob
marklandry 19 Jul, 2012
Thanx Bob -
Got this working - ie geocoding an address before form is submitted.
Here's what I have in case anyone else needs this:

In "custom code" (on load - after show html)
<?php
$doc =& JFactory::getDocument();
$doc->addScript('https://maps.googleapis.com/maps/api/js?sensor=false');
?>


In "load JS" (on load - after show html)

window.addEvent('domready', function() {
  $('address').addEvent('change', codeAddress);
  $('lat').addEvent('change', codeAddress);
  $('lng').addEvent('change', codeAddress);
});

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

function codeAddress() {
    
    var address = document.getElementById("address").value;
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var lattd = results[0].geometry.location.lat(); 
        var lngtd = results[0].geometry.location.lng();
        $('lat').value = lattd;
        $('lng').value = lngtd;

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

GreyHead 19 Jul, 2012
Hi Mark,

Well done.

Just a footnote looking at it in daylight. The Load JS action accepts PHP so - despite my previous posts - you could put the file loader code at the beginning of the code section there rather than in a separate Custom Code action.

Bob
This topic is locked and no more replies can be posted.