How to Save Current Location using Visualforce Pages

Visualforce Aug 12, 2014

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.

    if (navigator.geolocation) {
    } 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;

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 -->

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!


Phanindra Mangipudi

Salesforce, Lightning Web Componets, Node.Js, Angular 2+, Bootstrap