點擊Android中的谷歌地圖標記?

[英]Click on google maps marker in android?


I have an an activity where the main view is Google maps. And I set up a marker when the map is initially loaded, but when I click on it I am not able to get the locality or anything. The maps appears, but I can't click on the marker, or tap or tap on the screen and hold to create a new marker. basically it cannot do anything...And i can't figure out why! Hope you guys can see something that I am not seeing.

我有一個主要視圖是谷歌地圖的活動。我在最初加載地圖時設置了一個標記,但是當我點擊它時,我無法獲得地點或任何東西。將顯示地圖,但我無法單擊標記,或者點擊或點擊屏幕並按住以創建新標記。基本上它什么都做不了......我無法弄明白為什么!希望你們能看到我沒看到的東西。

Here is my main activity.

這是我的主要活動。

public class MapsActivity extends FragmentActivity {

    //Maps
    private GoogleMap mMap;
    //Marker
    private Marker marker;
    //Location
    private LocationListener locationListener = null;
    private LocationManager locationManager = null;
    private static final float DEFAULTZOOM = 15;
    private double longitude_mapsActivity;
    private double latitude_from_mapsActivity;
    private String cityName_mapsActivity;
    private String countryName_mapsActivity;
    //ProgressBar
    private ProgressBar myPB_MAPS;
    //Buttons
    private ImageButton fab_doneButton;

    //SearchEditText
    private EditText editText_Search;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(new OnMapReadyCallback() {
            @Override
            public void onMapReady(GoogleMap googleMap) {
                mMap = googleMap;
                LatLng sydney = new LatLng(-34, 151);
                mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
                mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
            }
        });
        //Get user current location.
        //myPB_MAPS = (ProgressBar) findViewById(R.id.myPB_MAPS);

        //initialize your map
        initMap();

        //FAB button
        fab_doneButton = (ImageButton) findViewById(R.id.activity_maps_FAB_done);
        fab_doneButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (countryName_mapsActivity == null) {
                    Toast.makeText(MapsActivity.this, "Location is null", Toast.LENGTH_SHORT).show();
                } else {
                    Global_Class.getInstance().getValue().countryName_GLOBAL = countryName_mapsActivity;
                    Global_Class.getInstance().getValue().cityName_GLOBAL = cityName_mapsActivity;
                    Global_Class.getInstance().getValue().longitude_user_GLOBAL = longitude_mapsActivity;
                    Global_Class.getInstance().getValue().latitude_user_GLOBAL = latitude_from_mapsActivity;
                    //Go to make sure we're sending all the GPS info, so we set geoLocationFromMapsIsPresent to true.
                    FinishCard.geoLocationFromMapsIsPresent();
                    FinishCard.setComingBackFromMaps();
                    Intent FinishCardIntent = new Intent(MapsActivity.this, FinishCard.class);
                    startActivity(FinishCardIntent);
                }

            }
        });

        //EditText
        editText_Search = (EditText) findViewById(R.id.maps_EditText);
        editText_Search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    performSearch();
                    return true;
                }
                return false;
            }

        });




        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    }

    private void performSearch()
    {
        String location = editText_Search.getText().toString();
        if(location.length() == 0)
        {
            Toast.makeText(this,"Please enter a location",Toast.LENGTH_SHORT).show();
            return;
        }
        //1-first step
        Geocoder gc = new Geocoder(this);
        List<Address> list = null;//For this function I only want a single address.
        try
        {
            //3-Third step
            list = gc.getFromLocationName(location,10);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        //4-Fourth step
        Address add = list.get(0);//Give me the first and only item of the list.

        //5-fifth step
        String locality = add.getLocality();//So if you enter Taj mahal you get Agra, the place where its at, thats what Address locality does.
        double lat = add.getLatitude();
        double lng = add.getLongitude();

        //GoToLocation() method
        gotoLocation(lat, lng, DEFAULTZOOM);

        //For Removing existing markers.
        if(marker != null)
        {
            marker.remove();
        }

        MarkerOptions options = new MarkerOptions()
                .title(locality)
                .position(new LatLng(lat, lng))
                .draggable(true);
        marker =  mMap.addMarker(options);
    }

    private void gotoLocation(double lat, double lng, float zoom)
    {
        LatLng ll = new LatLng(lat,lng);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(ll, zoom);
        mMap.moveCamera(update);

    }

    private void setMarker(String locality, String country, double lat, double lng)
    {
        if(marker != null)
        {
            marker.remove();
        }
        MarkerOptions options = new MarkerOptions()
                .title(locality)
                .position(new LatLng(lat, lng))
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE))
                .draggable(true);
        if(country.length() > 0)
        {
            options.snippet(country);//Background highlight TEXT SUPER IMPORTANT
        }
        //.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
        marker = mMap.addMarker(options);//So here we connect our marker to our map, which is used in initMap.

    }

    private void initMap()
    {
        if(mMap == null)
        {

            if(mMap != null)
            {
                mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener()
                {
                    @Override
                    public void onMapLongClick(LatLng ll) {
                        Geocoder gc = new Geocoder(MapsActivity.this);
                        List<Address> list = null;
                        try {
                            list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        Address add = list.get(0);
                        MapsActivity.this.setMarker(add.getLocality(), add.getCountryName(), ll.latitude, ll.longitude);//this is where we set the orange marker.
                        latitude_from_mapsActivity= ll.latitude;
                        longitude_mapsActivity= ll.longitude;
                        countryName_mapsActivity = add.getCountryName();
                        cityName_mapsActivity = add.getLocality();
                    }
                });

                mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                    @Override
                    public boolean onMarkerClick(Marker marker)
                    {
                        LatLng ll = marker.getPosition();
                        latitude_from_mapsActivity= ll.latitude;
                        longitude_mapsActivity = ll.longitude;
                        Geocoder gc = new Geocoder(MapsActivity.this);
                        //Global_Class.getInstance().getValue().cardLocality = "Paris";
                        List<Address> list = null;
                        try
                        {
                            list = gc.getFromLocation(ll.latitude, ll.longitude,1);

                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                        try
                        {
                            Address add = list.get(0);
                            countryName_mapsActivity = add.getCountryName();
                            cityName_mapsActivity = add.getLocality();
                            return false;

                        }
                        catch (IndexOutOfBoundsException e)
                        {
                            return false;
                        }


                    }
                });

                mMap.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() //If you want to drag the original google maps marker you use this method, if you comment this out it will use the orange one.
                {
                    @Override
                    public void onMarkerDragStart(Marker marker) {

                    }

                    @Override
                    public void onMarkerDrag(Marker marker) {

                    }

                    @Override
                    public void onMarkerDragEnd(Marker marker) {
                        Geocoder gc = new Geocoder(MapsActivity.this);
                        List<Address> list = null;
                        LatLng ll = marker.getPosition();
                        try {
                            list = gc.getFromLocation(ll.latitude, ll.longitude, 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                        Address add = list.get(0);
                        marker.setTitle(add.getLocality());
                        marker.setSnippet(add.getCountryName());
                        //marker.showInfoWindow();
                    }
                });
            }
        }
    }
}

Here is my xml

這是我的xml

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.daprlabs.swipedeck.GeoLocation.MapsActivity">


    <RelativeLayout
        android:layout_width="340dp"
        android:layout_height="50dp"
        android:background="#FFFFFF"
        android:elevation="10sp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp">

        <EditText
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:id="@+id/maps_EditText"
            android:imeOptions="actionSearch"
            android:inputType="text"/>
    </RelativeLayout>

    <ProgressBar
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:id="@+id/myPB_MAPS"
        android:layout_marginLeft="150dp"
        android:layout_marginTop="55dp"/>

    <ImageButton
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:background="@drawable/circle_fab"
        android:id="@+id/activity_maps_FAB_done"
        android:layout_gravity="right|bottom"
        android:src="@drawable/white_plus" />


</fragment>

2 个解决方案

#1


0  

You are contradicting yourself in your initMap().

你在initMap()中自相矛盾。

Remove the following if statement:

刪除以下if語句:

if (mMap == null)

Also only call initMap() after mapFragment.getMapAsync returns. At this point, you know your map is ready to go.

也只在mapFragment.getMapAsync返回后調用initMap()。此時,您知道您的地圖已准備就緒。

    mapFragment.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mMap = googleMap;
            LatLng sydney = new LatLng(-34, 151);
            mMap.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(15), 2000, null);
            initMap();
        }
    });

#2


0  

You are supposed to implement

你應該實施

OnMapReadyCallback

OnMapReadyCallback

And in turn override

反過來覆蓋

onMapReady

onMapReady

Now you can manipulate the Map within onMapReady. Before that, it is not certain that your Map has actually set properly.

現在您可以在onMapReady中操作Map。在此之前,您無法確定您的地圖是否已正確設置。

Anything that manipulates the Map like loading markers over it and setting marker click listeners has to happen in onMapReady.

任何操縱Map的東西,比如在它上面加載標記和設置標記點擊監聽器都必須在onMapReady中進行。

As an example of Map's manipulation at appropriate time, you can take hint from the following code where Map's camera is only set when it has properly set.

作為Map在適當時候進行操作的示例,您可以從以下代碼中獲取提示,其中Map的相機僅在正確設置時才設置。

    public class YourMapFragment extends Fragment implements OnMapReadyCallback { 
...
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentPosition,16));

    mMap.addMarker(new MarkerOptions()
            .position(currentPosition)
            .snippet("Lat:" + lat + "Lng:" + log));
}

    ...
    }

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/08/25/b75b0733b89d3649044d5425b3940dba.html



 
  © 2014-2022 ITdaan.com 联系我们: