如何在地图上添加标记onmaplong click?

时间:2018-05-11 06:11:40

标签: android google-maps

Address Dailoge这是一个片段,当我点击图片时,另一个活动(位置活动)开始谷歌地图打开。  这是Address Dailoge片段的代码 当地图打开时,我希望显示用户的当前位置,用户使用地图选择器从地图中选择位置 当用户选择我希望获取街道邮政编码的地址时,州,国家将其设置为表格。

public class AddressDialog extends DialogFragment {

    public interface AddressListener {
        void address(Address address);

        void editedAddress(Address locationModel, int index);
    }

    private static final String TAG = "AddressDialog";
    @BindView(R.id.addresslineone)
    FormAnimationView addresslineone;

    private GoogleApiClient mClient;

    @BindView(R.id.addresslinetwo)
    FormAnimationView addresslinetwo;

    @BindView(R.id.city)
    FormAnimationView cityView;

    @BindView(R.id.state)
    FormAnimationView stateView;

    @BindView(R.id.country)
    FormAnimationView countryView;

    private boolean isfromEdit;
    @BindView(R.id.pincode)
    FormAnimationView pincode;

    @BindView(R.id.edit_spinner_1)
    EditSpinner mEditSpinner1;


    private Address address = new Address();
    private AddressListener addressListener;
    private int index;

    @OnClick(R.id.closedialog)
    public void closeClick() {
        this.dismiss();
    }

    @BindView(R.id.searchmap)
    ImageView openmap;

    @OnClick(R.id.searchmap)
    public void searchmapclick() {
        startActivityForResult(new Intent(getActivity(), LocationActivity.class), 100);

    }

    @OnClick(R.id.addaddressimg)
    public void addClick() {


        if (addressListener != null && address != null) {


            if (!TextUtils.isEmpty(mEditSpinner1.getText()) &&
                    !TextUtils.isEmpty(addresslineone.getText())
                    && !TextUtils.isEmpty(addresslinetwo.getText())
                    && !TextUtils.isEmpty(cityView.getText())
                    && !TextUtils.isEmpty(stateView.getText())
                    && !TextUtils.isEmpty(pincode.getText())
                    && !TextUtils.isEmpty(countryView.getText())) {
                //locationModel.setAddressType(mEditSpinner1.getText().toString());
                //address.setCountry(addresslinetwo.getText().toString());
                // address.setLocality();

                //address.setLocality("");
                address.setRegion(stateView.getText().toString());
                address.setFormatted(addresslineone.getText().toString());
                address.setFormatted(addresslinetwo.getText().toString());
                address.setCountry(countryView.getText().toString());
                address.setLocality(cityView.getText().toString());
                // address.setState(stateView.getText().toString());
                address.setPostalCode(pincode.getText().toString());
                address.setStreetAddress(addresslineone.getText().toString());
                address.setStreetAddress(addresslinetwo.getText().toString());
                address.setType(mEditSpinner1.getText().toString());
                // address.setRegion();


                if (!isfromEdit) {
                    addressListener.address(address);
                } else {
                    addressListener.editedAddress(address, address.getIndex());
                }
                this.dismiss();
            } else {
                Toast.makeText(getActivity(), "All fields are mandetory", Toast.LENGTH_SHORT).show();
            }


        }
    }

    @Override
    public void onStart() {
        super.onStart();
        mClient.connect();
    }

    @Override
    public void onStop() {
        mClient.disconnect();
        super.onStop();
    }

//    @Override
//    public void onAttach(Context context) {
//        super.onAttach(context);
//        //addressListener = (AddressListener) context;
//    }

    public void setListener(AddressListener addressListener) {
        this.addressListener = addressListener;
    }

  /*  @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        final View view = View.inflate(getActivity(), R.layout.address_selection_view, null);

        Dialog dialog = new Dialog(getActivity(), R.style.DialogFragment);
        dialog.setContentView(view);
        return dialog;

    }*/



    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);

        // getDialog().getWindow().getWindowStyle().gets;


        View rootView = inflater.inflate(R.layout.address_selection_view, container, false);
        //  getDialog().setTitle("Simple Dialog");
        ButterKnife.bind(this, rootView);
        mClient = new GoogleApiClient
                .Builder(getContext())
                .addApi(Places.GEO_DATA_API)
                .addApi(Places.PLACE_DETECTION_API)
                .build();
        try {
            Address locationModel = (Address) getArguments().get("data");
            if (locationModel != null) {
                // getAddressDetails(locationModel.getAddress());
                address.setAddressId(locationModel.getAddressId());
                address.setFormatted("");
                address.setCountry(addresslinetwo.getText().toString());
                address.setLocality("");
                address.setRegion("");
                address.setPostalCode(pincode.getText().toString());
                address.setStreetAddress(addresslineone.getText().toString());
                address.setStreetAddress(addresslinetwo.getText().toString());

                addresslineone.setText(locationModel.getStreetAddress());
                addresslinetwo.setText(locationModel.getStreetAddress());
                /*addresslinetwo.setText(locationModel.getCountry());*/
                pincode.setText(locationModel.getPostalCode());

                mEditSpinner1.setText(locationModel.getType());
                countryView.setText(locationModel.getCountry());
                stateView.setText(locationModel.getRegion());
                cityView.setText(locationModel.getLocality());
                isfromEdit = true;

            }

        } catch (Exception e) {

        }

        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
    }

    private void init() {

        addresslineone.setHintMessage("Address Line 1 (Street / landmark)");
        addresslineone.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);

        addresslineone.setTintColor(Color.parseColor("#de3f5abd"));

        addresslineone.setFontStyle("fonts/Helvetica.otf");

        addresslinetwo.setHintMessage("Address Line 2 (City / Country)");
        addresslinetwo.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
        addresslinetwo.setTintColor(Color.parseColor("#de3f5abd"));
        addresslinetwo.setFontStyle("fonts/Helvetica.otf");


        pincode.setHintMessage("Post / Zip / Pin Code");
        pincode.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
        pincode.setFontStyle("fonts/Helvetica.otf");

        pincode.setTintColor(Color.parseColor("#de3f5abd"));

        stateView.setInputType(InputType.TYPE_CLASS_TEXT);
        stateView.setHintMessage("State");
        stateView.setTintColor(Color.parseColor("#de3f5abd"));
        stateView.setFontStyle("fonts/Helvetica.otf");


        countryView.setInputType(InputType.TYPE_CLASS_TEXT);
        countryView.setHintMessage("Country");
        countryView.setTintColor(Color.parseColor("#de3f5abd"));
        countryView.setFontStyle("fonts/Helvetica.otf");

        cityView.setInputType(InputType.TYPE_CLASS_TEXT);
        cityView.setHintMessage("City");
        cityView.setTintColor(Color.parseColor("#de3f5abd"));
        cityView.setFontStyle("fonts/Helvetica.otf");

        ListAdapter adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item,
                getResources().getStringArray(R.array.edits_array_1));
        mEditSpinner1.setAdapter(adapter);


    }

    public void getAddressDetails(String address) {
        StringBuilder stringBuilder = new StringBuilder();

        if (address != null) {
            String[] addressSlice = address.toString().split(", ");
            String country = addressSlice[addressSlice.length - 1];
            if (country != null) {
                addresslinetwo.setText(country);
                countryView.setText(country);
            }
            stringBuilder.append("Country:" + country);

            if (addressSlice.length > 1) {
                String[] stateAndPostalCode = addressSlice[addressSlice.length - 2].split(" ");
                if (stateAndPostalCode.length > 1) {
                    String postalCode = stateAndPostalCode[stateAndPostalCode.length - 1];
                    String state = "";
                    for (int i = 0; i < stateAndPostalCode.length - 1; i++) {
                        state += (i == 0 ? "" : " ") + stateAndPostalCode[i];
                    }
                    stringBuilder.append("PostalCode:" + postalCode);
                    stringBuilder.append("State:" + state);

                    if (postalCode != null) {
                        pincode.setText(postalCode);
                    }

                    if (state != null) {
                        stateView.setText("" + state);
                        //   pincode.setText(pincode.getText() + "," + state);
                    }

                } else {
                    String state = stateAndPostalCode[stateAndPostalCode.length - 1];
                    stringBuilder.append("State:" + state);
                    stateView.setText("" + state);


                }
            }
            String city = null;
            if (addressSlice.length > 2)
                city = addressSlice[addressSlice.length - 3].toString();

            if (city != null) {
                cityView.setText("" + city);
                // addresslinetwo.setText(addresslinetwo.getText() + "," + city);
                stringBuilder.append("City:" + city);

            }

            String stAddress1 = "";
            if (addressSlice.length == 4)
                stAddress1 = addressSlice[0];
            else if (addressSlice.length > 3) {
                String stAddress2 = addressSlice[addressSlice.length - 4];
                for (int i = 0; i < addressSlice.length - 4; i++) {
                    stAddress1 += (i == 0 ? "" : ", ") + addressSlice[i];
                }
            }
            stringBuilder.append("Address1:" + stAddress1);

            if (stAddress1 != null) {
                addresslineone.setText(stAddress1);
                // addresslineone.getText().replaceAll("null", "");
            }

        }
//        if(place.getLatLng()!=null)
//        {
//            String latitude = "" + place.getLatLng().latitude;
//            String longitude = "" + place.getLatLng().longitude;
//        }

        Log.e(TAG, "getAddressDetails: " + stringBuilder.toString());

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //Log.e(TAG, "onActivityResult: " + requestCode);
        if (requestCode == 100) {
            try {


                if (data.getExtras() != null && data.getExtras().getSerializable("data") != null) {
                    LocationModel locationModel = (LocationModel) data.getExtras().getSerializable("data");
                    if (locationModel != null) {
                        // addresslineone.setText(locationModel.getLocationname());
                        getAddressDetails(locationModel.getAddress());
                        //latitude = String.valueOf(locationModel.getLatitude());
                        //longitude = String.valueOf(locationModel.getLongitude());
                    }
                }
            } catch (Exception e) {

            }
        }
    }
}

以下是位置活动的代码 Map

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.planfisheye.fisheye.BaseActivity;
import com.planfisheye.fisheye.R;
import com.planfisheye.fisheye.adapters.NearByGetLocationParser;
import com.planfisheye.fisheye.adapters.PlacesAutoCompleteAdapter;
import com.planfisheye.fisheye.adapters.PlacesModel;
import com.planfisheye.fisheye.helper.CustomDialog;
import com.planfisheye.fisheye.models.LocationModel;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by venkateshmurthy on 24/12/16.
 */

public class LocationActivity extends BaseActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, PlaceSelectionListener {
    private static final String TAG = "LocationActivity";
    MapView mapView;
    GoogleMap map;
    private GoogleApiClient mClient;
    @BindView(R.id.autocompletesearch)
    AutoCompleteTextView autoSearch;
    private static final int REQUEST_SELECT_PLACE = 1000;
    private LatLng latlangObj;
    private String address;
    private String locationname;

    private CustomDialog mCustomDialog;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick(R.id.doneclick)
    public void doneClick() {

        if(latlangObj!=null) {
            LocationModel locationModel=new LocationModel();
            locationModel.setLatitude(latlangObj.latitude);
            locationModel.setLongitude(latlangObj.longitude);
            locationModel.setLocationname(locationname);
            locationModel.setAddress(address);
            Intent intent=new Intent();
            intent.putExtra("data",locationModel);
            setResult(13, intent);
            finish();

        }else {
            finish();
        }
        overridePendingTransition(R.anim.enter, R.anim.exit);

    }

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

        setContentView(R.layout.activity_location_select);
        ButterKnife.bind(this);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);

        mCustomDialog=new CustomDialog(this);
//        try {
//            Intent intent = new PlaceAutocomplete.IntentBuilder
//                    (PlaceAutocomplete.MODE_OVERLAY)
//                   // .setBoundsBias(BOUNDS_MOUNTAIN_VIEW)
//                    .build(this);
//            startActivityForResult(intent, REQUEST_SELECT_PLACE);
//        } catch (GooglePlayServicesRepairableException |
//                GooglePlayServicesNotAvailableException e) {
//            e.printStackTrace();
//        }
//        PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
//                getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
//        autocompleteFragment.setOnPlaceSelectedListener(this);
//        autocompleteFragment.setHint("Search a Location");
        mClient = new GoogleApiClient
                .Builder(this)
                .addApi(Places.GEO_DATA_API)
                .enableAutoManage(this, this)
                .addApi(Places.PLACE_DETECTION_API)
                .build();
        mClient.connect();
        autoSearch.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.autocomplete_list_item));
        autoSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                autoSearch.setText("");
            }
        });
        autoSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //CommonUtils.hideKeyBoard(getActivity());

                mCustomDialog.show();
                final PlacesModel hm = (PlacesModel) autoSearch.getAdapter().getItem(position);
                Log.e("place_id", "" + hm.getPlaceid());
                //  placetext.setText("" + hm.getDescription());
                //AIzaSyA9_CVo9IETbjjqqBHC1eEYesVsaMPflIk
                String[] codeInfo =
                        TextUtils.split(hm.getDescription(), ",");


                // getLatLng(hm.getPlaceid());
                Places.GeoDataApi.getPlaceById(mClient, hm.getPlaceid())
                        .setResultCallback(new ResultCallback<PlaceBuffer>() {
                            @Override
                            public void onResult(PlaceBuffer places) {

                                mCustomDialog.dismiss();
                                if (places.getStatus().isSuccess() && places.getCount() > 0) {
                                    final Place myPlace = places.get(0);
                                    //getAddressDetails(myPlace);
                                    Log.e("name", "Place found: " + myPlace.getName() + "\t" + myPlace.getAddress()+"\t"+myPlace.getLatLng());

                                    if(myPlace.getAddress()!=null) {
                                        address = myPlace.getAddress().toString();
                                    }
                                    latlangObj= myPlace.getLatLng();

                                    locationname=hm.getDescription();
                                    Log.e("latitude:", "" + latlangObj.latitude);
                                    Log.e("longitude:", "" + latlangObj.longitude);
                                    Marker marker = map.addMarker(new MarkerOptions()
                                            .position(new LatLng(latlangObj.latitude, latlangObj.longitude))
                                            .title("" + hm.getDescription()));
                                    marker.showInfoWindow();
                                    marker.setDraggable(true);
                                    map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
                                        @Override
                                        public void onMarkerDragStart(Marker marker) {

                                        }

                                        @Override
                                        public void onMarkerDrag(Marker marker) {

                                        }

                                        @Override
                                        public void onMarkerDragEnd(Marker marker) {


                                    map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
                                } else {
                                    Log.e("place", "Place not found");
                                }
                                places.release();
                            }
                        });
                autoSearch.setText(""+hm.getDescription());
                autoSearch.setSelection(autoSearch.getText().length());

            }
        });

        // Needs to call MapsInitializer before doing any CameraUpdateFactory calls
        MapsInitializer.initialize(this);

    }


    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
        mClient.disconnect();
    }


    @Override
    protected void onStart() {
        super.onStart();

    }

    @Override
    protected void onStop() {

        super.onStop();
    }


    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.map = googleMap;

    }

    @Override
    public void onPlaceSelected(Place place) {

    }

    @Override
    public void onError(Status status) {

    }


    private class NearbyLatlngTask extends AsyncTask<String, Integer, String> {

        String data = null;


        @Override
        protected String doInBackground(String... url) {
            try {
                data = downloadUrl(url[0]);
            } catch (Exception e) {
                Log.d("Background Task", e.toString());
            }
            return data;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(String result) {
            GetLatLngTask parserTask = new GetLatLngTask();

            // Start parsing the Google places in JSON format
            // Invokes the "doInBackground()" method of the class ParseTask
            parserTask.execute(result);
        }
    }

    /**
     * A class to parse the Google Places in JSON format
     */
    private class GetLatLngTask extends AsyncTask<String, Integer, List<HashMap<String, Double>>> {

        JSONObject jObject;

        // Invoked by execute() method of this object
        @Override
        protected List<HashMap<String, Double>> doInBackground(String... jsonData) {

            List<HashMap<String, Double>> places = null;
            NearByGetLocationParser nearPlaceJsonParser = new NearByGetLocationParser();

            try {
                jObject = new JSONObject(jsonData[0]);

                /** Getting the parsed data as a List construct */
                places = nearPlaceJsonParser.parse(jObject);

            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
            return places;
        }

        // Executed after the complete execution of doInBackground() method
        @Override
        protected void onPostExecute(List<HashMap<String, Double>> list) {

            // Clears all the existing markers
            //   mGoogleMap.clear();
            if (list != null) {
                for (int i = 0; i < list.size(); i++) {

                    // Creating a marker
                    MarkerOptions markerOptions = new MarkerOptions();

                    // Getting a place from the places list
                    HashMap<String, Double> hmPlace = list.get(i);

                    // Getting latitude of the place
                    double lat = hmPlace.get("lat");

                    // Getting longitude of the place
                    double lng = hmPlace.get("lng");

                    Log.e("lat", "lat" + lat);
                    Log.e("long", "long" + lng);
Toast.LENGTH_SHORT).show();

                }
            }
        }
    }

    /**
     * A method to download json data from url
     */
    private String downloadUrl(String strUrl) throws IOException {
        String data = "";
        InputStream iStream = null;
        HttpURLConnection urlConnection = null;
        try {
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url
            urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url
            urlConnection.connect();

            // Reading data from url
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb = new StringBuffer();

            String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            data = sb.toString();

            br.close();

        } catch (Exception e) {
            //Log.d("Exception while downloading url", e.toString());
        } finally {
            iStream.close();
            urlConnection.disconnect();
        }
        return data;
    }

    private void getLatLng(String placeID) {
        StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?placeid=" + placeID);
        sb.append("&key=AIzaSyBiV3T00af_2jM0Vinlcws2Gc6K7ktVp38");
        NearbyLatlngTask placesTask = new NearbyLatlngTask();

        // Invokes the "doInBackground()" method of the class PlaceTask
        placesTask.execute(sb.toString());
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }
}

1 个答案:

答案 0 :(得分:0)

检查一下,

map.setOnMapLongClickListener(new OnMapLongClickListener() {

        @Override
        public void onMapLongClick(LatLng latLng) {
           addMarker();
            }
    });

添加这是addMarker方法,

 private void addMarker() {
    // create marker
    MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
    googleMap.addMarker(marker);
}