Código Apex y Visualforce de FindNearby

Éste es el código que usaremos para el ejemplo de mostrar las cuentas cercanas a nosotros y que estén a menos de 1 Km de distancia.

Clase Apex FindNearby:

global with sharing class FindNearby {
    public FindNearby(ApexPages.StandardController controller) {}

    @RemoteAction
    // Find Accounts nearest a geolocation
    global static List<Account> getNearby(String lat, String lon) {
        // If geolocation is not set, use Plaza Santa Bárbara, 2, Madrid
        if(lat == null || lon == null || lat.equals("") || lon.equals("")) {
            lat = "40.427305";
            lon = "-3.696754";
        }

        // SOQL query to get the nearest warehouses
        String queryString =
            "SELECT Id, Name, Location__Longitude__s, Location__Latitude__s " +
            "FROM Account " +
            "WHERE DISTANCE(Location__c, GEOLOCATION("+lat+","+lon+"), \"km\") < 1 " +
            "ORDER BY DISTANCE(Location__c, GEOLOCATION("+lat+","+lon+"), \"km\") " +
            "LIMIT 10";

        // Run and return the query results
        return(database.Query(queryString));
    }
}

Página Visualforce FindNearbyAccountPage:

<apex:page sidebar="false" showheader="false" standardController="Account" extensions="FindNearby">
    <!-- Include in Google Maps API via JavaScript static resource -->
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js"></script>

    <!-- Setup the map to take up the whole window -->
    <style>
        html, body { height: 100%; }
        .page-map, .ui-content, #map-canvas { width: 100%; height:100%; padding: 0; }
        #map-canvas { height: min-height: 100%; }
    </style>

    <script>
        function initialize() {
            var lat, lon;

            // If we can, get the position of the user via device geolocation
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(function(position){
                    lat = position.coords.latitude;
                    lon = position.coords.longitude;
                    console.log(lat);
                    console.log(lon);

                    // Use Visualforce JavaScript Remoting to query for nearby accounts
                    Visualforce.remoting.Manager.invokeAction("{!$RemoteAction.FindNearby.getNearby}", lat, lon,
                        function(result, event){
                            if (event.status) {
                                console.log(result);
                                createMap(lat, lon, result);
                            } else if (event.type === "exception") {
                                //exception case code
                            } else {
                            }
                        },
                        {escape: true}
                    );
                });
            } else {
                // Set default values for map if the device does not have geolocation capabilities
                /** Plaza Santa Bárbara, 2, Madrid **/
                lat = 40.427305;
                lon = -3.696754;

                var result = [];
                createMap(lat, lon, result);
            }
        }

        function createMap(lat, lon, accounts){
            // Get the map div, and center the map at the proper geolocation
            var currentPosition = new google.maps.LatLng(lat,lon);
            var mapDiv = document.getElementById("map-canvas");
            var map = new google.maps.Map(mapDiv, {
                center: currentPosition,
                zoom: 14,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            // Set a marker for the current location
            var positionMarker = new google.maps.Marker({
                map: map,
                position: currentPosition,
                icon: "https://maps.google.com/mapfiles/ms/micons/green.png"
            });

            // Keep track of the map boundary that holds all markers
            var mapBoundary = new google.maps.LatLngBounds();
            mapBoundary.extend(currentPosition);

            // Set markers on the map from the @RemoteAction results
            var acc;
            for(var i=0; i<accounts.length;i++){
                acc = accounts[i];
                console.log(acc);
                setupMarker(acc, map, mapBoundary);
            }

            // Resize map to neatly fit all of the markers
            map.fitBounds(mapBoundary);
        }

        function setupMarker(acc, map, mapBoundary){
            var accountNavUrl;

            // Determine if we are in Salesforce1 and set navigation link appropriately
            try{
                if(sforce.one){
                    accountNavUrl =
                        "javascript:sforce.one.navigateToSObject(\"" + acc.Id + "\")";
                }
            } catch(err) {
                console.log(err);
                accountNavUrl = "\\" + acc.Id;
            }

            var accountDetails =
                "<a href=\"" + accountNavUrl + "\">" + acc.Name + "</a>";

            // Create the callout that will pop up on the marker
            var infowindow = new google.maps.InfoWindow({
                content: accountDetails
            });

            // Place the marker on the map
            var marker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(
                                acc.Location__Latitude__s,
                                acc.Location__Longitude__s)
            });
            mapBoundary.extend(marker.getPosition());

            // Add the action to open up the panel when it is marker is clicked
            google.maps.event.addListener(marker, "click", function(){
                infowindow.open(map, marker);
            });
        }

        // Fire the initialize function when the window loads
        google.maps.event.addDomListener(window, "load", initialize);
    </script>

    <!--  All content is rendered by the Google Maps code -->
    <!--  This minimal HTML justs provide a target for GMaps to write to -->
    <body style="font-family: Arial; border: 0 none;">
        <div id="map-canvas"></div>
    </body>
</apex:page>
Anuncios

Un comentario en “Código Apex y Visualforce de FindNearby

  1. Pingback: Salesforce III Developer Day en Madrid el Miércoles 22 de Octubre de 2014 | ticMind Consulting Blog - Partner Salesforce CRM

Responder

Introduce tus datos o haz clic en un icono para iniciar sesión:

Logo de WordPress.com

Estás comentando usando tu cuenta de WordPress.com. Cerrar sesión /  Cambiar )

Google+ photo

Estás comentando usando tu cuenta de Google+. Cerrar sesión /  Cambiar )

Imagen de Twitter

Estás comentando usando tu cuenta de Twitter. Cerrar sesión /  Cambiar )

Foto de Facebook

Estás comentando usando tu cuenta de Facebook. Cerrar sesión /  Cambiar )

Conectando a %s