How to Save Current Location using Visualforce Pages

Follow these points,

  1. Create a New Custom field of type Geo-Location under your Standard/Custom Object (skip if already created)
  2. we use navigator.geolocation under script tags, so its prompts us/opens under address bar like shown below, please allow/Okay it

    FYI: sample co-ords will be like
    Latitude: 17.5065977
    Longitude: 78.3364009

STEP1: Please add following <script> tags under <apex:page> tag in your Visualforce page.

<script>
    if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
    } else {
    alert("Geolocation is not supported by this browser.");
    }

    function showPosition(pos) {
  	/*put logs as shown to check whether populating correctly or not*/
    	console.log("Latitude: " + pos.coords.latitude + "\nLongitude: " + pos.coords.longitude);
    // storing into long (id of hidden field in form tags)
    	document.getElementById("{!$Component.fId.latField}").value = pos.coords.latitude;
    // storing into long (id of hidden field in form tags) 	document.getElementById('{!$Component.fId.longField}').value = pos.coords.longitude;
}
</script>

FYI: if you're using pageBlocks, pageBlockSection etc you need to use document.getElementById as follows => {!$Component.fId.pb.pbs.inplong}

STEP2: Add Hidden elements to form as shown

<apex:form id="fId">
    <apex:inputHidden id="hdnField2" value="{!latt}" />
    <apex:inputHidden id="hdnField3" value="{!longt}" />
    <!-- rest of code here -->
</apex:form>

STEP3: Save hidden field elements to Apex controller like this

public class controllerClass {
  public decimal latt { get; set; }       
  public decimal longt { get; set; }

  public void saveRec() {
    sObject ws = new sObject();
    /*intialize your object if already done not needed, then assign as follows*/

    ws.Last_Saved_Location__Latitude__s = latt;
    ws.Last_Saved_Location__Longitude__s = longt;
    insert ws; //insert/update/upsert which ever suits you
  }
}

Thats It. Navigate to your Visualforce page, create/update record, check you Geo-Location fields

Any Problem, comment me I can help you out!

Thanks!!!

Subscribe to Phanindra Mangipudi

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe