किसी पता फ़ॉर्म में स्थान ऑटोकंप्लीट जोड़ना

डिलीवरी का पता, बिलिंग जानकारी या इवेंट की जानकारी भरते समय, जगह के अपने-आप पूरे होने की सुविधा वाले फ़ॉर्म को चालू करने से, उपयोगकर्ताओं को पता जानकारी डालते समय कीस्ट्रोक और गलतियों को कम करने में मदद मिलती है. यह ट्यूटोरियल, 'अपने-आप पूरा होने की सुविधा' वाली इनपुट फ़ील्ड को चालू करने के लिए ज़रूरी चरणों के बारे में बताता है. साथ ही, पते के फ़ॉर्म के फ़ील्ड में, उपयोगकर्ता के चुने गए पते से पते के कॉम्पोनेंट की जानकारी शामिल करता है. साथ ही, चुने गए पते को मैप पर दिखाता है, ताकि विज़ुअल पुष्टि में मदद मिल सके.

वीडियो: 'जगह की जानकारी अपने-आप पूरा होने की सुविधा' सुविधा की मदद से पते के फ़ॉर्म को बेहतर बनाना

पते के फ़ॉर्म

Android

iOS

वेब

Google Maps Platform, मोबाइल प्लैटफ़ॉर्म और वेब के लिए जगह के अपने-आप पूरे होने वाला विजेट उपलब्ध कराता है. पिछले आंकड़ों में दिखाया गया विजेट, खोज डायलॉग बॉक्स उपलब्ध कराता है. इसमें पहले से अपने-आप पूरा होने की सुविधा मौजूद होती है. इस सुविधा को जगह के हिसाब से खोज के लिए ऑप्टिमाइज़ भी किया जा सकता है.

कोड पाएं

GitHub से, Android डेमो के डेटा स्टोर करने की जगह के लिए Google Places SDK टूल का क्लोन बनाएं या उसे डाउनलोड करें.

गतिविधि का Java वर्शन देखें:

    /*
 * Copyright 2022 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.placesdemo;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewStub;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.example.placesdemo.databinding.AutocompleteAddressActivityBinding;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMapOptions;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MapStyleOptions;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.libraries.places.api.Places;
import com.google.android.libraries.places.api.model.AddressComponent;
import com.google.android.libraries.places.api.model.AddressComponents;
import com.google.android.libraries.places.api.model.Place;
import com.google.android.libraries.places.api.model.TypeFilter;
import com.google.android.libraries.places.api.net.PlacesClient;
import com.google.android.libraries.places.widget.Autocomplete;
import com.google.android.libraries.places.widget.model.AutocompleteActivityMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static android.Manifest.permission.ACCESS_FINE_LOCATION;
import static com.google.maps.android.SphericalUtil.computeDistanceBetween;

/**
 * Activity for using Place Autocomplete to assist filling out an address form.
 */
@SuppressWarnings("FieldCanBeLocal")
public class AutocompleteAddressActivity extends AppCompatActivity implements OnMapReadyCallback {

    private static final String TAG = "ADDRESS_AUTOCOMPLETE";
    private static final String MAP_FRAGMENT_TAG = "MAP";
    private LatLng coordinates;
    private boolean checkProximity = false;
    private SupportMapFragment mapFragment;
    private GoogleMap map;
    private Marker marker;
    private PlacesClient placesClient;
    private View mapPanel;
    private LatLng deviceLocation;
    private static final double acceptedProximity = 150;

    private AutocompleteAddressActivityBinding binding;

    View.OnClickListener startAutocompleteIntentListener = view -> {
        view.setOnClickListener(null);
        startAutocompleteIntent();
    };

    private final ActivityResultLauncher<Intent> startAutocomplete = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent intent = result.getData();
                    if (intent != null) {
                        Place place = Autocomplete.getPlaceFromIntent(intent);

                        // Write a method to read the address components from the Place
                        // and populate the form with the address components
                        Log.d(TAG, "Place: " + place.getAddressComponents());
                        fillInAddress(place);
                    }
                } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                    // The user canceled the operation.
                    Log.i(TAG, "User canceled autocomplete");
                }
            });

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        binding.autocompleteAddress1.setOnClickListener(startAutocompleteIntentListener);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = AutocompleteAddressActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // Retrieve a PlacesClient (previously initialized - see MainActivity)
        placesClient = Places.createClient(this);

        // Attach an Autocomplete intent to the Address 1 EditText field
        binding.autocompleteAddress1.setOnClickListener(startAutocompleteIntentListener);

        // Update checkProximity when user checks the checkbox
        CheckBox checkProximityBox = findViewById(R.id.checkbox_proximity);
        checkProximityBox.setOnCheckedChangeListener((view, isChecked) -> {
            // Set the boolean to match user preference for when the Submit button is clicked
            checkProximity = isChecked;
        });

        // Submit and optionally check proximity
        Button saveButton = findViewById(R.id.autocomplete_save_button);
        saveButton.setOnClickListener(v -> saveForm());

        // Reset the form
        Button resetButton = findViewById(R.id.autocomplete_reset_button);
        resetButton.setOnClickListener(v -> clearForm());
    }

    private void startAutocompleteIntent() {

        // Set the fields to specify which types of place data to
        // return after the user has made a selection.
        List<Place.Field> fields = Arrays.asList(Place.Field.ADDRESS_COMPONENTS,
                Place.Field.LAT_LNG, Place.Field.VIEWPORT);

        // Build the autocomplete intent with field, country, and type filters applied
        Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields)
                .setCountries(Arrays.asList("US"))
                .setTypesFilter(new ArrayList<String>() {{
                    add(TypeFilter.ADDRESS.toString().toLowerCase());
                }})
                .build(this);
        startAutocomplete.launch(intent);
    }

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        map = googleMap;
        try {
            // Customise the styling of the base map using a JSON object defined
            // in a string resource.
            boolean success = map.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));

            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 15f));
        marker = map.addMarker(new MarkerOptions().position(coordinates));
    }

    private void fillInAddress(Place place) {
        AddressComponents components = place.getAddressComponents();
        StringBuilder address1 = new StringBuilder();
        StringBuilder postcode = new StringBuilder();

        // Get each component of the address from the place details,
        // and then fill-in the corresponding field on the form.
        // Possible AddressComponent types are documented at https://goo.gle/32SJPM1
        if (components != null) {
            for (AddressComponent component : components.asList()) {
                String type = component.getTypes().get(0);
                switch (type) {
                    case "street_number": {
                        address1.insert(0, component.getName());
                        break;
                    }

                    case "route": {
                        address1.append(" ");
                        address1.append(component.getShortName());
                        break;
                    }

                    case "postal_code": {
                        postcode.insert(0, component.getName());
                        break;
                    }

                    case "postal_code_suffix": {
                        postcode.append("-").append(component.getName());
                        break;
                    }

                    case "locality":
                        binding.autocompleteCity.setText(component.getName());
                        break;

                    case "administrative_area_level_1": {
                        binding.autocompleteState.setText(component.getShortName());
                        break;
                    }

                    case "country":
                        binding.autocompleteCountry.setText(component.getName());
                        break;
                }
            }
        }

        binding.autocompleteAddress1.setText(address1.toString());
        binding.autocompletePostal.setText(postcode.toString());

        // After filling the form with address components from the Autocomplete
        // prediction, set cursor focus on the second address line to encourage
        // entry of sub-premise information such as apartment, unit, or floor number.
        binding.autocompleteAddress2.requestFocus();

        // Add a map for visual confirmation of the address
        showMap(place);
    }

    private void showMap(Place place) {
        coordinates = place.getLatLng();

        // It isn't possible to set a fragment's id programmatically so we set a tag instead and
        // search for it using that.
        mapFragment = (SupportMapFragment)
                getSupportFragmentManager().findFragmentByTag(MAP_FRAGMENT_TAG);

        // We only create a fragment if it doesn't already exist.
        if (mapFragment == null) {
            mapPanel = ((ViewStub) findViewById(R.id.stub_map)).inflate();
            GoogleMapOptions mapOptions = new GoogleMapOptions();
            mapOptions.mapToolbarEnabled(false);

            // To programmatically add the map, we first create a SupportMapFragment.
            mapFragment = SupportMapFragment.newInstance(mapOptions);

            // Then we add it using a FragmentTransaction.
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.confirmation_map, mapFragment, MAP_FRAGMENT_TAG)
                    .commit();
            mapFragment.getMapAsync(this);
        } else {
            updateMap(coordinates);
        }
    }

    private void updateMap(LatLng latLng) {
        marker.setPosition(latLng);
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15f));
        if (mapPanel.getVisibility() == View.GONE) {
            mapPanel.setVisibility(View.VISIBLE);
        }
    }

    private void saveForm() {
        Log.d(TAG, "checkProximity = " + checkProximity);
        if (checkProximity) {
            checkLocationPermissions();
        } else {
            Toast.makeText(
                            this,
                            R.string.autocomplete_skipped_message,
                            Toast.LENGTH_SHORT)
                    .show();
        }
    }

    private void clearForm() {
        binding.autocompleteAddress1.setText("");
        binding.autocompleteAddress2.getText().clear();
        binding.autocompleteCity.getText().clear();
        binding.autocompleteState.getText().clear();
        binding.autocompletePostal.getText().clear();
        binding.autocompleteCountry.getText().clear();
        if (mapPanel != null) {
            mapPanel.setVisibility(View.GONE);
        }
        binding.autocompleteAddress1.requestFocus();
    }

    // Register the permissions callback, which handles the user's response to the
    // system permissions dialog. Save the return value, an instance of
    // ActivityResultLauncher, as an instance variable.
    private final ActivityResultLauncher<String> requestPermissionLauncher =
            registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
                if (isGranted) {
                    // Since ACCESS_FINE_LOCATION is the only permission in this sample,
                    // run the location comparison task once permission is granted.
                    // Otherwise, check which permission is granted.
                    getAndCompareLocations();
                } else {
                    // Fallback behavior if user denies permission
                    Log.d(TAG, "User denied permission");
                }
            });

    private void checkLocationPermissions() {
        if (ContextCompat.checkSelfPermission(this, ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            getAndCompareLocations();
        } else {
            requestPermissionLauncher.launch(
                    ACCESS_FINE_LOCATION);
        }
    }

    @SuppressLint("MissingPermission")
    private void getAndCompareLocations() {
        // TODO: Detect and handle if user has entered or modified the address manually and update
        // the coordinates variable to the Lat/Lng of the manually entered address. May use
        // Geocoding API to convert the manually entered address to a Lat/Lng.
        LatLng enteredLocation = coordinates;
        map.setMyLocationEnabled(true);

        FusedLocationProviderClient fusedLocationClient =
                LocationServices.getFusedLocationProviderClient(this);

        fusedLocationClient.getLastLocation()
                .addOnSuccessListener(this, location -> {
                    // Got last known location. In some rare situations this can be null.
                    if (location == null) {
                        return;
                    }

                    deviceLocation = new LatLng(location.getLatitude(), location.getLongitude());
                    Log.d(TAG, "device location = " + deviceLocation);
                    Log.d(TAG, "entered location = " + enteredLocation.toString());

                    // Use the computeDistanceBetween function in the Maps SDK for Android Utility Library
                    // to use spherical geometry to compute the distance between two Lat/Lng points.
                    double distanceInMeters = computeDistanceBetween(deviceLocation, enteredLocation);
                    if (distanceInMeters <= acceptedProximity) {
                        Log.d(TAG, "location matched");
                        // TODO: Display UI based on the locations matching
                    } else {
                        Log.d(TAG, "location not matched");
                        // TODO: Display UI based on the locations not matching
                    }
                });
    }
}
    

एपीआई चालू करना

इन सुझावों को लागू करने के लिए, आपको Google Cloud Console में इन एपीआई को चालू करना होगा:

सेटअप करने के बारे में ज़्यादा जानकारी के लिए, अपना Google Cloud प्रोजेक्ट सेट अप करना लेख पढ़ें.

इनपुट फ़ील्ड में ऑटोकंप्लीट की सुविधा जोड़ी जा रही है

इस सेक्शन में पता फ़ॉर्म में 'जगह की जानकारी ऑटोकंप्लीट' सुविधा को जोड़ने का तरीका बताया गया है.

जगह के अपने-आप पूरे होने की सुविधा का विजेट जोड़ना

Android में, ऑटोकंप्लीट इंटेंट का इस्तेमाल करके ऑटोकंप्लीट विजेट जोड़ा जा सकता है, जो पते की लाइन 1 के इनपुट फ़ील्ड से, ऑटोकंप्लीट की सुविधा को लॉन्च करता है, जहां उपयोगकर्ता अपना पता डालना शुरू कर देता है. जब वे लिखना शुरू करेंगे, तो वे ऑटोकंप्लीट सुझावों की सूची से अपना पता चुन सकेंगे.

सबसे पहले, ActivityResultLauncher का इस्तेमाल करके, ऐक्टिविटी लॉन्चर तैयार करें. इसमें, लॉन्च की गई गतिविधि के नतीजे को सुना जाएगा. नतीजे के कॉलबैक में एक जगह से जुड़ा ऑब्जेक्ट होगा, जो उस पते से मेल खाता होगा जिसे उपयोगकर्ता ने अपने-आप पूरा होने की सुविधा से चुना है.

    private final ActivityResultLauncher<Intent> startAutocomplete = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent intent = result.getData();
                    if (intent != null) {
                        Place place = Autocomplete.getPlaceFromIntent(intent);

                        // Write a method to read the address components from the Place
                        // and populate the form with the address components
                        Log.d(TAG, "Place: " + place.getAddressComponents());
                        fillInAddress(place);
                    }
                } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                    // The user canceled the operation.
                    Log.i(TAG, "User canceled autocomplete");
                }
            });

इसके बाद, 'जगह की जानकारी अपने-आप पूरी होने वाली सुविधा' इंटेंट के फ़ील्ड, जगह, और टाइप प्रॉपर्टी तय करें और उसे Autocomplete.IntentBuilder की मदद से बनाएं. आखिर में, पिछले कोड सैंपल में बताए गए ActivityResultLauncher का इस्तेमाल करके इंटेंट को लॉन्च करें.

    private void startAutocompleteIntent() {

        // Set the fields to specify which types of place data to
        // return after the user has made a selection.
        List<Place.Field> fields = Arrays.asList(Place.Field.ADDRESS_COMPONENTS,
                Place.Field.LAT_LNG, Place.Field.VIEWPORT);

        // Build the autocomplete intent with field, country, and type filters applied
        Intent intent = new Autocomplete.IntentBuilder(AutocompleteActivityMode.OVERLAY, fields)
                .setCountries(Arrays.asList("US"))
                .setTypesFilter(new ArrayList<String>() {{
                    add(TypeFilter.ADDRESS.toString().toLowerCase());
                }})
                .build(this);
        startAutocomplete.launch(intent);
    }

स्थान ऑटोकंप्लीट की सुविधा से मिलने वाले पते को मैनेज करना

पहले ActivityResultLauncher की जानकारी देने से यह भी तय हुआ है कि कॉलबैक में गतिविधि का नतीजा वापस मिलने पर क्या किया जाना चाहिए. अगर उपयोगकर्ता ने किसी सुझाव को चुना है, तो उसे नतीजे के ऑब्जेक्ट में मौजूद इंटेंट में डिलीवर किया जाएगा. इंटेंट को Autocomplete.IntentBuilder ने बनाया था, इसलिए Autocomplete.getPlaceFromIntent() तरीके से जगह से जुड़े ऑब्जेक्ट को निकाला जा सकता है.

    private final ActivityResultLauncher<Intent> startAutocomplete = registerForActivityResult(
            new ActivityResultContracts.StartActivityForResult(),
            result -> {
                if (result.getResultCode() == Activity.RESULT_OK) {
                    Intent intent = result.getData();
                    if (intent != null) {
                        Place place = Autocomplete.getPlaceFromIntent(intent);

                        // Write a method to read the address components from the Place
                        // and populate the form with the address components
                        Log.d(TAG, "Place: " + place.getAddressComponents());
                        fillInAddress(place);
                    }
                } else if (result.getResultCode() == Activity.RESULT_CANCELED) {
                    // The user canceled the operation.
                    Log.i(TAG, "User canceled autocomplete");
                }
            });

इसके बाद, Place.getAddressComponents() को कॉल करें और पता फ़ॉर्म में पते के हर कॉम्पोनेंट को उसके इनपुट फ़ील्ड से मैच करें. साथ ही, फ़ील्ड में वैल्यू को उपयोगकर्ता की चुनी हुई जगह से अपने-आप भरें.

पता फ़ॉर्म फ़ील्ड की जानकारी अपने-आप भरने का एक उदाहरण, इस पेज के कोड पाएं सेक्शन में दिए गए सैंपल कोड के fillInAddress तरीके में शेयर किया जाता है.

मैन्युअल तरीके से डाले गए पते के बजाय, अनुमान से पते का डेटा कैप्चर करने से, यह पक्का करने में मदद मिलती है कि पता कितना सटीक है. साथ ही, इससे यह पक्का करने में मदद मिलती है कि पता पहले से मौजूद है और उस पर डिलीवर किया जा सकता है. साथ ही, इससे उपयोगकर्ता कीस्ट्रोक का कम इस्तेमाल होता है.

स्थान ऑटोकंप्लीट को लागू करते समय ध्यान रखने वाली बातें

'जगह की जानकारी अपने-आप पूरी होने की सुविधा' में कई विकल्प हैं. इनकी मदद से, विजेट के अलावा दूसरी चीज़ों का भी इस्तेमाल किया जा सकता है. किसी जगह का मिलान सही तरीके से करने के लिए, कई सेवाओं का इस्तेमाल किया जा सकता है.

  • ADDRESS फ़ॉर्म के लिए, मोहल्ले के पूरे पतों से मेल खाने को सीमित करने के लिए टाइप पैरामीटर को address पर सेट करें. 'अपने-आप पूरा होने की सुविधा के अनुरोध' के लिए काम करने वाले टाइप के बारे में ज़्यादा जानें.

  • अगर आपको दुनिया भर में जानकारी नहीं खोजनी है, तो सही पाबंदियां और पक्षपात तय करें. ऐसे कई पैरामीटर हैं, जिनका इस्तेमाल पक्षपात करने या किसी मैच को सिर्फ़ खास क्षेत्रों तक सीमित करने के लिए किया जा सकता है.

    • किसी एरिया की रेक्टैंग्युलर बाउंड्री सेट करने के लिए, RectangularBounds का इस्तेमाल करें. यह पक्का करने के लिए setLocationRestriction() का इस्तेमाल करें कि सिर्फ़ उन एरिया के पते दिखाए गए हों.

    • कुछ देशों में जवाबों को प्रतिबंधित करने के लिए, setCountries() का इस्तेमाल करें.

  • अगर मैच में कुछ फ़ील्ड शामिल नहीं हो पाते हैं, तो ऐसे फ़ील्ड में बदलाव किए जा सकते हैं. साथ ही, ज़रूरत पड़ने पर ग्राहकों को पता अपडेट करने की अनुमति दें. जगह की जानकारी अपने-आप भर जाने की सुविधा के ज़रिए दिखाए गए ज़्यादातर पतों में अपार्टमेंट, सुइट या यूनिट नंबर जैसे सब-प्रिमाइस नंबर नहीं होते हैं. ऐसे में, फ़ोकस को पते की दूसरी लाइन पर ले जाया जा सकता है, ताकि ज़रूरत पड़ने पर उपयोगकर्ता वह जानकारी भर सके.

पते की विज़ुअल पुष्टि करना

पता डालते समय, उपयोगकर्ताओं को मैप पर पते की विज़ुअल पुष्टि दिखाएं. इससे उपयोगकर्ताओं को पता चलता है कि पता सही है.

नीचे दिए गए डायग्राम में, पते के नीचे एक मैप दिखाया गया है. इस मैप को, डाले गए पते पर पिन किया गया है.

नीचे दिया गया उदाहरण Android में मैप जोड़ने के बुनियादी तरीके को फ़ॉलो किया गया है. ज़्यादा जानकारी के लिए दस्तावेज़ देखें.

SupportMapFragment को जोड़ा जा रहा है

सबसे पहले, लेआउट एक्सएमएल फ़ाइल में SupportMapFragment फ़्रैगमेंट जोड़ें.

    <fragment
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:id="@+id/confirmation_map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

इसके बाद, अगर फ़्रैगमेंट अभी तक मौजूद नहीं है, तो प्रोग्राम के हिसाब से उसे जोड़ें.

    private void showMap(Place place) {
        coordinates = place.getLatLng();

        // It isn't possible to set a fragment's id programmatically so we set a tag instead and
        // search for it using that.
        mapFragment = (SupportMapFragment)
                getSupportFragmentManager().findFragmentByTag(MAP_FRAGMENT_TAG);

        // We only create a fragment if it doesn't already exist.
        if (mapFragment == null) {
            mapPanel = ((ViewStub) findViewById(R.id.stub_map)).inflate();
            GoogleMapOptions mapOptions = new GoogleMapOptions();
            mapOptions.mapToolbarEnabled(false);

            // To programmatically add the map, we first create a SupportMapFragment.
            mapFragment = SupportMapFragment.newInstance(mapOptions);

            // Then we add it using a FragmentTransaction.
            getSupportFragmentManager()
                    .beginTransaction()
                    .add(R.id.confirmation_map, mapFragment, MAP_FRAGMENT_TAG)
                    .commit();
            mapFragment.getMapAsync(this);
        } else {
            updateMap(coordinates);
        }
    }

फ़्रैगमेंट को हैंडल करना और कॉलबैक को रजिस्टर करना

  1. फ़्रैगमेंट को हैंडल करने के लिए, FragmentManager.findFragmentById तरीके को कॉल करें और उसे अपनी लेआउट फ़ाइल में फ़्रैगमेंट के रिसॉर्स आईडी को पास करें. अगर आपने फ़्रैगमेंट को डाइनैमिक तौर पर जोड़ा है, तो इस चरण को छोड़ दें, क्योंकि आपने हैंडल को पहले ही वापस पा लिया है.

  2. फ़्रैगमेंट पर कॉलबैक सेट करने के लिए, getMapAsync तरीके को कॉल करें.

उदाहरण के लिए, अगर आपने फ़्रैगमेंट को स्टैटिक तरीके से जोड़ा है:

Kotlin



val mapFragment = supportFragmentManager
    .findFragmentById(R.id.map) as SupportMapFragment
mapFragment.getMapAsync(this)

      

Java


SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
    .findFragmentById(R.id.map);
mapFragment.getMapAsync(this);

      

मैप पर मार्कर जोड़ना और स्टाइल बनाना

मैप तैयार होने पर स्टाइल सेट करें, कैमरे को बीच में लाएं, और डाले गए पते के निर्देशांकों पर मार्कर जोड़ें. नीचे दिया गया कोड, JSON ऑब्जेक्ट में बताई गई स्टाइल का इस्तेमाल करता है या आपके पास ऐसे मैप आईडी को लोड करने का विकल्प भी है जिसे क्लाउड पर आधारित मैप स्टाइलिंग से तय किया गया है.

    @Override
    public void onMapReady(@NonNull GoogleMap googleMap) {
        map = googleMap;
        try {
            // Customise the styling of the base map using a JSON object defined
            // in a string resource.
            boolean success = map.setMapStyle(
                    MapStyleOptions.loadRawResourceStyle(this, R.raw.style_json));

            if (!success) {
                Log.e(TAG, "Style parsing failed.");
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Can't find style. Error: ", e);
        }
        map.moveCamera(CameraUpdateFactory.newLatLngZoom(coordinates, 15f));
        marker = map.addMarker(new MarkerOptions().position(coordinates));
    }

(पूरा कोड सैंपल देखें)

मैप नियंत्रण अक्षम किया जा रहा है

अतिरिक्त मैप कंट्रोल (जैसे कंपास, टूलबार या पहले से मौजूद दूसरी सुविधाएं) के बिना जगह की जानकारी दिखाकर मैप को आसान बनाने के लिए, उन कंट्रोल को बंद करें जो ज़रूरी नहीं हैं. Android पर, सीमित इंटरैक्टिविटी देने के लिए लाइट मोड चालू किया जा सकता है.