Newer Version Available
Example of Building Map Data in Apex
Apex code gives you complete control over the results that are returned and used for the map and markers. You can also use Apex to return results that are from outside Salesforce.
- The JavaScript block at the beginning illustrates how you can access the browser’s built-in ability to ask for the user’s current location. This code updates a visible form field. However, you can easily use a hidden form field instead to avoid showing the raw latitude and longitude with its unlikely level of precision.
- The first <apex:pageBlockSection> contains a short form for submitting the user’s location in the POSTBACK request. For illustration purposes it’s visible and requires a click, but that’s not required.
- In the second <apex:pageBlockSection>, the map itself is simple, requiring only
five lines of code. All the complexity is in the {!locations} expression, which accesses a property in the Apex
controller.
Note the use of the rendered attribute, which takes the value of the {!resultsAvailable} expression. This expression is another Apex property, and using it with the rendered attribute hides the map section when locations aren’t available to place on the map.
- The locations property is a list of Map<String,Double> elements. This list holds the location data in a format that’s directly usable by the <apex:mapMarker> component.
- The currentPosition property captures the position information that’s submitted from the page’s form. This property also ensures that if the form submission is empty, a valid default value is provided. (A more robust implementation would do more error checking on the form input.)
- The resultsAvailable property, noted in the earlier description of the Visualforce markup.
- The findNearby action method is called when the Go! <apex:commandButton> is pressed. This method does all the work, executing a custom SOQL query and massaging the results into the locations property format.
If you want to use the title attribute of <apex:mapMarker> to provide additional information (for example, the name of the warehouse), you have several options. If your method is returning sObjects, you can reference the appropriate fields in your Visualforce markup. If you’re creating new objects directly, as we are here, you can create an inner class that combines the location map object with the title string. You then return a collection of the inner class objects to the page.