+ Start a Discussion
NM AdminNM Admin 

How to get current logged in users location(Lat, Long,Address) and display on visual force page?

Thanks in advance!

I want to fetch current logged in users latitude , longitude and the street, city, state, postal code, country etc... and display the map on the visualforce page.
May I have help in this...?

Welcome to youe suggestions!

Steven NsubugaSteven Nsubuga
Assuming that the latitude , longitude and the street, city, state, postal code, country etc fields are cusom fields on the User object. Apex controller
public class MapController {

  private List<User> users = new List<User>();

  public MapController() {
    users = [SELECT Id,
                FROM User
                   Id =:UserInfo.getUserId()];


  public List<List<String>> getGpsLocations() {
    List<List<String>> gpsLocations = new List<List<String>>();
    for (User u : users) {
      String[] addressList = new String[] {String.valueOf(vea.Latitude__c), 
    return gpsLocations;
Visualforce page.
<apex:page controller="MapController">
    <apex:pageBlock mode="maindetail">
        <apex:pageBlockSection columns="1" title="Coverage Area">
            <script src="https://maps.google.com/maps/api/js?sensor=false"></script>
            <div id="map" style="width: 400px; height: 400px; margin-left:100px;"></div>
            <script type="text/javascript">
                var locations = {!GpsLocations};       
                var iconURLPrefix = 'https://maps.google.com/mapfiles/ms/icons/';
                var icon = iconURLPrefix + 'red-dot.png';

                var shadow = {
                  anchor: new google.maps.Point(15,33),
                  url: iconURLPrefix + 'msmarker.shadow.png'
                var map = new google.maps.Map(document.getElementById('map'), {
                  zoom: 8,
                  center: new google.maps.LatLng(locations[0][0], locations[0][1])),
                  mapTypeId: google.maps.MapTypeId.ROADMAP,
                  mapTypeControl: true,
                  streetViewControl: false,
                  panControl: false,
                  zoomControlOptions: {
                     position: google.maps.ControlPosition.RIGHT_BOTTOM

                var infowindow = new google.maps.InfoWindow({
                  maxWidth: 160

                var marker;
                var markers = new Array();

                // Add the markers and infowindows to the map
                for (var i = 0; i < locations.length; i++) {      
                  marker = new google.maps.Marker({
                    position: new google.maps.LatLng(locations[i][0], locations[i][1]),
                    map: map,
                    icon: icon,
                    shadow: shadow

                  google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                      infowindow.open(map, marker);
                  })(marker, i));
                function AutoCenter() {
                  //  Create a new viewpoint bound
                  var bounds = new google.maps.LatLngBounds();
                  //  Go through each...
                  $.each(markers, function (index, marker) {
                  //  Fit these bounds to the map
Something along these lines should get the job done.

NM AdminNM Admin
Thanks Steven,

Tried with this not getting expected outcome.
Any other way? OR fetch address(street, city, state, country) from latitude and longitude.
I can fetch latitude and longitude but I'm not able to fetch address fields.

Here is the current code of visual force page which fetching lat, long. Can we fetch address using this latitude and longitude??
<apex:page showHeader="false" controller="JourneyTrackerController"
           sidebar="false" setup="true" standardStylesheets="false">
        <meta content="width = device-width"/>
        <script src="/mobileclient/api/mobileforce.js"></script>
            function geoFindMe() {
            var output = document.getElementById("out");
            if (!navigator.geolocation){
                output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
            function success(position) {
                var latitude  = position.coords.latitude;
                var longitude = position.coords.longitude;
                output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';
                var img = new Image();
                img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";
            function error() {
                output.innerHTML = "Unable to retrieve your location";
            output.innerHTML = "<p>Locating…</p>";
            navigator.geolocation.getCurrentPosition(success, error);
        // create an interval calling the specified function every 10 seconds.
        //setInterval(function(){ geoFindMe();}, 10000);
    <apex:form id="frm">
        <apex:actionFunction name="iFoundYou" action="{!iFoundYou}" rerender="frm">     
            <apex:param id="lat" name="latitude" value="" assignTo="{!valueLat}"/>
            <apex:param id="long" name="longitude" value="" assignTo="{!valueLong}"/>
         <!--Learn about this code on MDN: https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation -->
        <p><button type="Hidden" style="display:none" onclick="geoFindMe()" >Show my location</button></p>
        <div id="out"></div>

Controller to store the lat, long in the custom object.
public class JourneyTrackerController {
	public Decimal valueLong { get; set; }
    public Decimal valueLat { get; set; }
    public PageReference iFoundYou() {
        // Do something interesting with the values - like persisting them to a database
        Location__c LatLong = new Location__c(Name = 'Test Name',Location__Latitude__s = valueLat,Location__Longitude__s = valueLong,Date_Time__c = System.now()); 
        insert  LatLong; // DML Operations
        return null;

By using this code can we fetch address value(street, city, state, country)..??

Steven NsubugaSteven Nsubuga
I had assumed you merely wanted a GPS marker on the map, that is why I shared the code that I did. To get address value in the manner that you want would require you to read up on the Google Maps API, to get that type of address. It is called Reverse Geocoding (https://developers.google.com/maps/documentation/javascript/geocoding#ReverseGeocoding).
Steven NsubugaSteven Nsubuga
Take a look at this as well (https://stackoverflow.com/questions/22545809/reverse-geocoding-in-php-request). It is the PHP version but can be modified into an Apex version. The format is
 "https://maps.googleapis.com/maps/api/geocode?latlng=" + latitude + "," + longitude + "&sensor=false&location_type=ROOFTOP&result_type=street_address";
but it returns JSON.
NM AdminNM Admin
Thanks Steven,

I also want GPS marker and want to track the sales persons journey(at which locations the particular sales person is visited). Display map and get street,city, state,country as well .

I implemented your code that you shared but don't see anything on the page..