Solved

Need Javascript to pass address field to a function (Google Maps API)

Posted on 2008-10-22
4
1,285 Views
Last Modified: 2012-08-13
I'm working on an implementation of the Google Maps API and am running into a bit of a problem.  Currently, I've got a pop-up box next to a set of latitude/longitude boxes.  The pop-up allows the user to punch in their address and hit submit, and via Javascript, the Lat/Long are displayed.  The user then copies and pastes the information back into the parent form which gets saved in a database for future map generation.

The problem is that this solution is evidently incompatible with Internet Explorer, but more importantly it's a big waste of time.  What I'd like to do is keep the pop-up link where it is, but rather than have it pop up another window, have it query the address field above and then run the routine to collect the latitude/longitude and populate the field.

Here's what I've got now on the main form:

<label for="formAddress1">Address:</label>
<input type="text" name="formAddress1" id="formAddress1" value="">
<br class="clear">
<label for="formAddress2">Address (line 2):</label>
<input type="text" name="formAddress2" id="formAddress2" value="">
<br class="clear">
<label for="formCity">City:</label>
<input type="text" name="formCity" id="formCity" value="">
<br class="clear">
<label for="formState">State:</label>
<select name="formState" id="formState">
<option value="">Please Select</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
...etc...
</select>
<br class="clear">
<label for="formZip">Zip:</label>
<input type="text" name="formZip" id="formZip" value="">
<br class="clear">            
<label for="formLat">Latitude:</label>
<input type="text" name="formLat" id="formLat" value="">
<input type="text" name="formLong" id="formLong" value="">
<a href="javascript:popUp('/account_faq.asp#coordinates');"><img src="/images/form_question.gif" class="question" border="0"></a>
<br class="clear">

That opens up to my popup with the Google Maps API:
<form action="#" onsubmit="showAddress(this.address.value); return false">
            <input type="text" size="60" name="address" value="" />
            <input type="image" src="/images/btn_find_coordinates.gif" class="submit_account">
      </form>
      <table border="0" cellpadding="0" cellspacing="0" width="228">
            <tr>
                  <td width="100"><b>Latitude</b></td>
                  <td id="lat"></td>
            </tr>
            <tr>
                  <td width="100"><b>Longitude</b></td>
                  <td id="lng"></td>
            </tr>
      </table>
      <div id="map">
            <br/>
      </div>

Which is handled by this included file:
function load(lat,lng) {
  if (GBrowserIsCompatible()) {
      var map = new GMap2(document.getElementById("map"));
      map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
      var center = new GLatLng(lat, lng);
      map.setCenter(center, 9);
      geocoder = new GClientGeocoder();
      var marker = new GMarker(center, {draggable: true});  
      map.addOverlay(marker);
      document.getElementById("lat").innerHTML = center.lat().toFixed(5);
      document.getElementById("lng").innerHTML = center.lng().toFixed(5);

  GEvent.addListener(marker, "dragend", function() {
   var point = marker.getPoint();
        map.panTo(point);
   document.getElementById("lat").innerHTML = point.lat().toFixed(5);
   document.getElementById("lng").innerHTML = point.lng().toFixed(5);

      });


 GEvent.addListener(map, "moveend", function() {
        map.clearOverlays();
var center = map.getCenter();
        var marker = new GMarker(center, {draggable: true});
        map.addOverlay(marker);
        document.getElementById("lat").innerHTML = center.lat().toFixed(5);
   document.getElementById("lng").innerHTML = center.lng().toFixed(5);


 GEvent.addListener(marker, "dragend", function() {
  var point =marker.getPoint();
       map.panTo(point);
  document.getElementById("lat").innerHTML = point.lat().toFixed(5);
       document.getElementById("lng").innerHTML = point.lng().toFixed(5);

      });

      });

  }
}

   function showAddress(address) {
   var map = new GMap2(document.getElementById("map"));
   map.addControl(new GSmallMapControl());
   map.addControl(new GMapTypeControl());
   if (geocoder) {
      geocoder.getLatLng(
        address,
        function(point) {
            if (!point) {
              alert(address + " not found");
            } else {
        document.getElementById("formLat").innerHTML = point.lat().toFixed(5);
   document.getElementById("formLng").innerHTML = point.lng().toFixed(5);
       map.clearOverlays()
            map.setCenter(point, 14);
var marker = new GMarker(point, {draggable: true});  
       map.addOverlay(marker);

      GEvent.addListener(marker, "dragend", function() {
  var pt = marker.getPoint();
       map.panTo(pt);
  document.getElementById("formLat").innerHTML = pt.lat().toFixed(5);
       document.getElementById("formLng").innerHTML = pt.lng().toFixed(5);
      });


 GEvent.addListener(map, "moveend", function() {
        map.clearOverlays();
var center = map.getCenter();
        var marker = new GMarker(center, {draggable: true});
        map.addOverlay(marker);
        document.getElementById("lat").innerHTML = center.lat().toFixed(5);
   document.getElementById("lng").innerHTML = center.lng().toFixed(5);

 GEvent.addListener(marker, "dragend", function() {
 var pt = marker.getPoint();
      map.panTo(pt);
document.getElementById("lat").innerHTML = pt.lat().toFixed(5);
   document.getElementById("lng").innerHTML = pt.lng().toFixed(5);
      });

      });

            }
        }
      );
  }
}


So, what I'd like to do is keep the link where it is but instead of popping up another window, have it populate the formLat and formLong fields with the result of showAddress, I believe, which in turn is getting its data from formAddress1, formCity, formState, and formZip.  Anyone able to point me in the right direction?  Please keep in mind that I'm only slightly above beginner level when talking about JavaScript.

Thanks very much in advance!
0
Comment
Question by:saoirse1916
  • 2
  • 2
4 Comments
 
LVL 23

Accepted Solution

by:
Tiggerito earned 500 total points
ID: 22784953
it sounds a bit like something I implemented on my website:

http://www.mccreath.org.uk/Article/Google-Maps-Location-Finder_42.aspx

The javascript for this is in the http://www.mccreath.org.uk/Shared/GoogleMaps.js file.

I've included a simpilfication of the code that reads an address field, finds the lat/lng and populates the relevant fields.

It assumes input fields with ids "address", "lat" & "lng". And function moveEditorMarkerAddress() needs to be called to update the lat/lng fields


var ClientGeocoder = new GClientGeocoder();

function moveEditorMarkerAddress() { 

    ClientGeocoder.getLocations(document.getElementById("address").value,  moveEditorMarkerAddressResponse);

}
 

function moveEditorMarkerAddressResponse(response) {

    if (!response || response.Status.code != 200) {

        alert("Sorry, we were unable to geocode that address: "+ response.Status);

    } else {

        place = response.Placemark[0];

        point = new GLatLng(place.Point.coordinates[1],

                            place.Point.coordinates[0]);
 
 

        document.getElementById("lat").value = point.lat(); 

        document.getElementById("lng").value = point.lng();

    }

}

Open in new window

0
 
LVL 8

Author Comment

by:saoirse1916
ID: 22786038
That works great!  Is there a way to add in the city, state, and zip to the lookup?  Something like this (again, forgive the incorrect JavaScript syntax:

ClientGeocoder.getLocations(document.getElementById("address").value + ", " + document.getElementByID("city").value + ", " + document.getElementByID("state").value + " " + document.getElementByID("zip").value,  moveEditorMarkerAddressResponse);

When I try that, I get an error so I'm assuming I've screwed it up somehow.
0
 
LVL 23

Expert Comment

by:Tiggerito
ID: 22787037
javascript is case sensitive so make sure your getElementByID = getElementById.

Do a check to see if your getting the field data correct first...

alert(document.getElementById("address").value + ", " + document.getElementById("city").value + ", " + document.getElementById("state").value + " " + document.getElementById("zip").value);


0
 
LVL 8

Author Comment

by:saoirse1916
ID: 22788057
Bingo, that must have been it.  Thanks very much!
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now