Mostrar ubicaciones de clientes mediante Fiori Map Control

  • Prensa Shift dos veces y escribiendo styles.xml abierto styles.xml.

  • Confirmar estilo AppTheme como:

    <style name="AppTheme" parent="FioriTheme">
    
  • Agregue la siguiente dependencia a la aplicación build.gradle archivo en el objeto de dependencia.

    implementation group: 'com.sap.cloud.android', name: 'google-maps', version: sdkVersion
    
  • Crear nuevo Archivo de recursos de diseño en res/layout llamado detail_panel.xml y sustituya el siguiente código por su contenido.

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:layout_constraintVertical_weight="100">
    
        <TextView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:paddingTop="4dp"
            android:paddingLeft="4dp"
            android:text="Default panel content goes here" />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • Crear nuevo Archivo de recursos de diseño en res/layout llamado search_auto_complete.xml y reemplácelo con el siguiente código:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <androidx.appcompat.widget.AppCompatTextView
            android:id="@+id/search_auto_complete_text"
            android:layout_width="match_parent"
            android:layout_height="50dp" />
    
    </LinearLayout>
    
  • En Android Studio, con el explorador de proyectos, navegue hasta app > java > com.sap.wizapp > mdui > customers.

  • Haga clic derecho y seleccione Nuevo > Actividad > Actividad vacía.

  • Colocar Nombre de la actividad ser – estar CustomersFioriMapActivity.

  • Hacer clic Finalizar.

  • Reemplazar el contenido del archivo recién creado CustomersFioriMapActivity.java con el siguiente código:

    package com.sap.wizapp.mdui.customers;
    
    import android.content.Context;
    import android.content.Intent;
    import android.location.Address;
    import android.location.Geocoder;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.widget.ImageButton;
    
    import com.google.android.gms.maps.CameraUpdateFactory;
    import com.google.android.gms.maps.GoogleMap;
    import com.google.android.gms.maps.model.CameraPosition;
    import com.google.android.gms.maps.model.LatLng;
    import com.google.android.gms.maps.model.Marker;
    import com.sap.cloud.android.odata.espmcontainer.Customer;
    import com.sap.cloud.android.odata.espmcontainer.ESPMContainer;
    import com.sap.cloud.android.odata.espmcontainer.ESPMContainerMetadata;
    import com.sap.cloud.mobile.fiori.maps.FioriMarkerOptions;
    import com.sap.cloud.mobile.fiori.maps.FioriPoint;
    import com.sap.cloud.mobile.fiori.maps.LegendButton;
    import com.sap.cloud.mobile.fiori.maps.LocationButton;
    import com.sap.cloud.mobile.fiori.maps.SettingsButton;
    import com.sap.cloud.mobile.fiori.maps.ZoomExtentButton;
    import com.sap.cloud.mobile.fiori.maps.google.GoogleFioriMapView;
    import com.sap.cloud.mobile.fiori.maps.google.GoogleMapActionProvider;
    import com.sap.cloud.mobile.fiori.maps.google.GoogleMapViewModel;
    import com.sap.cloud.mobile.odata.DataQuery;
    import com.sap.wizapp.R;
    import com.sap.wizapp.app.SAPWizardApplication;
    import com.sap.wizapp.mdui.BundleKeys;
    import com.sap.wizapp.service.SAPServiceManager;
    
    import java.io.IOException;
    import java.util.Arrays;
    import java.util.List;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    public class CustomersFioriMapActivity extends AppCompatActivity implements GoogleFioriMapView.OnMapCreatedListener {
        private GoogleFioriMapView mGoogleFioriMapView;
        private boolean mUseClustering = false;
        private int mMapType;
        private HashMap<String, LatLng> locations = new HashMap<String, LatLng>();  // Used for demo purposes to speed up the process of converting an address to lat, long
        private HashMap<String, FioriMarkerOptions> markers = new HashMap<String, FioriMarkerOptions>();  // Used to associate an address with a marker for search
        private ArrayList<String> addresses = new ArrayList<String>();  // Used to populate the list of addresses that are searchable
    
        GoogleMapActionProvider mActionProvider;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            Intent intent = getIntent();
            setContentView(R.layout.activity_customers_fiori_map);
    
            mGoogleFioriMapView = findViewById(R.id.googleFioriMap);
            mGoogleFioriMapView.onCreate(savedInstanceState);
    
            if (savedInstanceState != null) {
                mUseClustering = savedInstanceState.getBoolean("UseClustering", false);
                mMapType = savedInstanceState.getInt("MapType", GoogleMap.MAP_TYPE_NORMAL);
            }
            mGoogleFioriMapView.setOnMapCreatedListener(this);
        }
    
        /**
         * Manipulates the map once available.
         * This callback is triggered when the map is ready to be used.
         * This is where we can add markers or lines, add listeners or move the camera. In this case,
         * we just add a marker near Toronto, Canada.
         */
        @Override
        public void onMapCreated() {
            mActionProvider = new GoogleMapActionProvider(mGoogleFioriMapView, this);
            // For demo purposes, speed up the lookup of address details.
            // Will use Geocoder to translate an address to a LatLng if address is not in this list
            locations.put("Wilmington, Delaware, US", new LatLng(39.744655, -75.5483909));
            locations.put("Antioch, Illinois, US", new LatLng(42.4772418, -88.0956396));
            locations.put("Santa Clara, California, US", new LatLng(37.354107899999995, -121.9552356));
            locations.put("Hermosillo, MX", new LatLng(29.0729673, -110.9559192));
            locations.put("Bismarck, North Dakota, US", new LatLng(46.808326799999996, -100.7837392));
            locations.put("Ottawa, CA", new LatLng(45.4215296, -75.69719309999999));
            locations.put("México, MX", new LatLng(23.634501, -102.55278399999999));
            locations.put("Boca Raton, Florida, US", new LatLng(26.368306399999998, -80.1289321));
            locations.put("Carrollton, Texas, US", new LatLng(32.9756415, -96.8899636));
            locations.put("Lombard, Illinois, US", new LatLng(41.8800296, -88.00784349999999));
            locations.put("Moorestown, US", new LatLng(39.9688817, -74.948886));
            addCustomersToMap();
    
            // Setup toolbar buttons and add to the view.
            SettingsButton settingsButton = new SettingsButton(mGoogleFioriMapView.getToolbar().getContext());
            LegendButton legendButton = new LegendButton(mGoogleFioriMapView.getToolbar().getContext());
            LocationButton locationButton = new LocationButton(mGoogleFioriMapView.getToolbar().getContext());
            ZoomExtentButton extentButton = new ZoomExtentButton(mGoogleFioriMapView.getToolbar().getContext());
            ImageButton[] buttons = {settingsButton, legendButton, locationButton, extentButton};
            mGoogleFioriMapView.getToolbar().addButtons(Arrays.asList(buttons));
    
            // Setup draggable bottom panel
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View detailView = inflater.inflate(R.layout.detail_panel, null);
            mGoogleFioriMapView.setDefaultPanelContent(detailView);
    
            mActionProvider.setClustering(false);
    
            LatLng currentPosition = ((GoogleMapViewModel)mActionProvider.getMapViewModel()).getLatLng();
            float currentZoom = ((GoogleMapViewModel)mActionProvider.getMapViewModel()).getZoom();
            if (currentPosition != null && currentZoom != 0) {
                // Position the camera after a lifecycle event.
                mGoogleFioriMapView.getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(currentPosition, currentZoom));
            } else {
                // Move the camera to the centre of North America
                LatLng centre = new LatLng(39.8283, -98.5795);
                mGoogleFioriMapView.getMap().animateCamera(CameraUpdateFactory.newLatLng(centre));
            }
    
            FioriMapSearchView mFioriMapSearchView = findViewById(R.id.fiori_map_search_view);
            if (mFioriMapSearchView != null) {
                SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
                mFioriMapSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
                mFioriMapSearchView.setAdapter(new ArrayAdapter<String>(CustomersFioriMapActivity.this, R.layout.search_auto_complete, R.id.search_auto_complete_text, addresses));
                mFioriMapSearchView.setThreshold(2);
                mFioriMapSearchView.setOnItemClickListener((parent, view, position, id) -> {
                    mFioriMapSearchView.setQuery(parent.getItemAtPosition(position).toString(), false);
                    searchResultSelected((String) parent.getItemAtPosition(position));
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(mFioriMapSearchView.getWindowToken(), 0);
                });
            }
        }
    
        private void searchResultSelected(String selectedSearchResult) {
            LatLng latLng = locations.get(selectedSearchResult);
            if (latLng != null) {
                // Center the marker.
                mGoogleFioriMapView.getMap().moveCamera(CameraUpdateFactory.newLatLng(latLng));
                // Select the marker (or cluster the marker is in).
                mActionProvider.selectMarker(markers.get(selectedSearchResult));
            }
        }
    
        // Methods overriding the lifecycle events are required for FioriMapView to run properly
        @Override
        public void onStart() {
            super.onStart();
            mGoogleFioriMapView.onStart();
        }
    
        @Override
        public void onResume() {
            super.onResume();
            mGoogleFioriMapView.onResume();
        }
    
        @Override
        public void onPause() {
            super.onPause();
            mGoogleFioriMapView.onPause();
        }
    
        @Override
        public void onStop() {
            super.onStop();
            mGoogleFioriMapView.onStop();
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
            mGoogleFioriMapView.onDestroy();
        }
    
        @Override
        protected void onSaveInstanceState(Bundle bundle) {
            super.onSaveInstanceState(bundle);
            mGoogleFioriMapView.onSaveInstanceState(bundle);
    
            bundle.putBoolean("UseClustering", mUseClustering);
            bundle.putInt("MapType", mMapType);
        }
    
        @Override
        public void onLowMemory() {
            super.onLowMemory();
            mGoogleFioriMapView.onLowMemory();
        }
    
        private LatLng getCustomerLatLongFromAddress(String address) {
            // import android.location.Address;
            List<Address> addresses;
            LatLng latLng = locations.get(address);
            if (latLng != null) {
                return latLng;
            }
    
            // String strAddress = "Wilmington, Delaware";
            Geocoder coder = new Geocoder(this);
    
            try {
                // May throw an IOException
                addresses = coder.getFromLocationName(address, 5);
                if (addresses == null || addresses.size() == 0) {
                    return null;
                }
    
                Address location = addresses.get(0);
                latLng = new LatLng(location.getLatitude(), location.getLongitude());
                return latLng;
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        }
    
        private void addCustomerMarkerToMap(Customer customer) {
            LatLng latLng = getCustomerLatLongFromAddress(customer.getCity() + ", " + customer.getCountry());
            if (latLng != null) {
                FioriMarkerOptions customerMarker = new FioriMarkerOptions.Builder()
                    .tag(customer)
                    .point(new FioriPoint(latLng.latitude, latLng.longitude))
                    .title(customer.getFirstName() + " " + customer.getLastName())
                    .legendTitle("Customer")
                    .build();
                mActionProvider.addMarker(customerMarker);
                markers.put(customer.getCity() + ", " + customer.getCountry(), customerMarker);
                mGoogleFioriMapView.getMap().moveCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }
    
        private void addCustomersToMap() {
            DataQuery query = new DataQuery()
                    .from(ESPMContainerMetadata.EntitySets.customers)
                    .where(Customer.country.equal("US")
                    .or(Customer.country.equal("CA"))
                    .or(Customer.country.equal("MX")));
            SAPServiceManager sapServiceManager = ((SAPWizardApplication) getApplication()).getSAPServiceManager();
            ESPMContainer espmContainer = sapServiceManager.getESPMContainer();
            espmContainer.getCustomersAsync(query, (List<Customer> customers) -> {
                for (Customer customer : customers) {
                    addCustomerMarkerToMap(customer);
                    addresses.add(customer.getCity() + ", " + customer.getCountry());
                }
                mActionProvider.doExtentsAction();
            }, (RuntimeException re) -> {
                Log.d("", "An error occurred during async query:  " + re.getMessage());
            });
        }
    }
    
  • Prensa Transferir dos veces y escribiendo activity_customers_fiori_map.xml abierto activity_customers_fiori_map.xml.

  • Sustituya el siguiente código por su contenido:

    <?xml version="1.0" encoding="utf-8"?>
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".mdui.customers.CustomersFioriMapActivity">
    
        <com.sap.cloud.mobile.fiori.maps.google.GoogleFioriMapView
            android:id="@+id/googleFioriMap"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            />
    
    </androidx.constraintlayout.widget.ConstraintLayout>
    
  • En Windows, presione Ctrl+N, o, en una Mac, presione command+Oy escriba EntitySetListActivity abierto EntitySetListActivity.java.

  • En Windows, presione Ctrl+F, o, en una Mac, presione command+Fy busque CustomersMapActivity.class.

  • Sustituir CustomersMapActivity.class le CustomersFioriMapActivity.class para que el usuario lo toque Clientes, la aplicación irá a la actividad recién agregada con un mapa de Fiori.

  • En Windows, presione Ctrl+Shift+N, o, en una Mac, presione command+Shift+Oy escriba AndroidManifest abierto AndroidManifest.xml.

  • En Windows, presione Ctrl+F, o, en una Mac, presione command+Fy busque CustomersFioriMapActivity.

  • Cambie la actividad para especificar el NoActionBar tema, que evitará que se muestre una barra de actividad en la actividad.

    <activity android:name=".mdui.customers.CustomersFioriMapActivity"
        android:theme="@style/AppTheme.NoActionBar">
    </activity>
    
  • Ejecute la aplicación.

    Debería poder ver marcadores en la pantalla que representan a los clientes.

    Los usuarios pueden usar la barra de búsqueda en la parte superior de la pantalla para encontrar marcadores. Por ejemplo, entrada Illinois o MX.

    La barra de herramientas lateral proporciona iconos para el diálogo de configuración, la leyenda del marcador, la ubicación actual y el zoom al tamaño de los marcadores en el mapa.

    El botón de acción flotante se abre en la esquina inferior derecha del panel de edición de anotaciones, lo que brinda la capacidad de dibujar puntos, líneas y polígonos en el mapa.

    El panel inferior es donde se pueden mostrar datos adicionales para un marcador seleccionado.

  • Deja un comentario

    Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

    Salir de la versión móvil