Sep 13, 2016

Using Google Maps to populate your form Latitude and Longitude

I needed to have a user easily enter a latitude and longitude where there might not be a true address, so I created a simple script to populate form variables when a user doubleclicks a Google Map.
The below is just javascript and html which uses the Google Map API V2 to place a map on the page which by default centers the map when you doubleclick.
The function that is fired in a dblclick event will then set the 2 form variables and leave a marker behind to help the user know where they clicked.
You will need to change the center points and the form names, but all this could be dynamically set as well.
Hope you can use this in your apps.
Note: you will need to fix the 2 InvalidTag's with script.  
<InvalidTag type="text/javascript">
// JavaScript Document
var cm_map;
var centerLon = '-81.655651';
var centerLat = '30.332184';
var zoomLevel = 12;
var latforminput = '';
var lngforminput = '';
var marker;
function cm_load() {  
    // create the map and display in div name cm_map
    cm_map = new GMap2(document.getElementById("cm_map"));
    cm_map.addControl(new GLargeMapControl());
    cm_map.addControl(new GMapTypeControl());
cm_map.setCenter(new GLatLng( centerLat, centerLon), zoomLevel);
// initialize vars for form fields to populate
latforminput = document.getElementById("latinput");
lngforminput = document.getElementById("lnginput");
// On Dblclick set form fields and leave a marker
GEvent.addListener(cm_map, "dblclick", function(x,ll) {
latforminput.value =;
lngforminput.value = ll.lng();
marker = new GMarker(ll, {draggable: false});
    //alert('lat:' + +  ' lon:' + ll.lng() );
setTimeout('cm_load()', 500);
<!---  Get Google Map API V2 and set Google key--->
<InvalidTag src=""
<!--- Map Div --->
<div id="cm_map" style="width:300px; height:300px">
<!--- Sample Form with values that will be populated when user Double Clicks on map--->
<form name="setlatlng">
Lat: <input type="text" name="lat"  id="latinput" value=""> <br />
Lng: <input type="text" name="lng"  id="lnginput" value="">

No comments:

Post a Comment