Tell Me More: About the Code

Let’s take a look at some of the code behind our Visualforce page that finds warehouses.

FindNearby Apex Class Query

This snippet is a dynamic SOQL query that uses variables passed in from the Visualforce page to find warehouses within 20 miles of the device accessing the page. This page works on any mobile device and HTML5–enabled desktop browser.

If the page is unable to obtain the location, the search is centered on San Francisco. If you test this from a browser, you might have to approve that the page can access your location depending on your device security settings.

Visualforce Page initialize Function

The initialize function in the Visualforce page uses the HTML5 geolocation API to get the coordinates of the user. The browser gets the position without using any plug-ins or external libraries, and then uses JavaScript remoting to invoke the getNearby function in the Apex controller and passes in the coordinates.

Visualforce Page Redirect Code

The page FindNearbyWarehousesPage uses the Google Maps JavaScript API v3 to plot the nearby warehouses on a map. We resize the map based on the records returned by the SOQL query and plot each record as marker on the map.

The most important piece of the code is where we determine whether or not the page is being viewed in the Salesforce1 app. If it is, the redirect link to the warehouse record must be coded slightly differently. If the page runs in the Salesforce1 app, we must use the navigateToSobjectRecord method to go to the record detail page but still stay in the app. We can check this with a simple try/catch construct, and then set the redirect link accordingly.