无法使用Marker类的getPosition()方法访问标记位置

时间:2015-08-07 12:44:22

标签: android

无法使用Marker类的getPosition()方法访问当前标记位置。

代码:

 package com.example.deepak.vibring;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
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 java.io.IOException;
import java.util.List;

/**
 * Created by deepak on 8/2/2015.
 */
public class AddNewLocationActivity extends Activity {
    GoogleMap googleMap;
    EditText edtLocation;
    Marker marker;
    List<Address> addressList;
    VibRIngDatabase vibRIngDatabase;
    double latitude, longitude;
    Geocoder geocoder;
    LatLng latLng;
    String locationAddress;
    AlertDialog.Builder dialogBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_addnewlocation);
        createMapView();// Rendering the Google Map in the fragment
        addMarkerAtCurrent(); // Adding marker at the current location of the device
        mapClick(); // On clicking the map
        vibRIngDatabase = new VibRIngDatabase(this);
    }

    //Display the Google Map inside the fragment
    private void createMapView() {
        /**
         * Catch the null pointer exception that
         * may be thrown when initialising the map
         */
        try {
            if (googleMap == null) {
                googleMap = ((MapFragment) getFragmentManager().findFragmentById(
                        R.id.map)).getMap();
                googleMap.setMyLocationEnabled(true); //To See my current location

                /**
                 * If the map is still null after attempted initialisation,
                 * show an error to the user
                 */
                if (googleMap == null) {
                    Toast.makeText(getApplicationContext(),
                            "Error creating map", Toast.LENGTH_SHORT).show();
                }
            }
        } catch (NullPointerException exception) {
            Log.e("mapApp", exception.toString());
        }
    }

    // Adding marker to the current location
    public void addMarkerAtCurrent() {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        // Create a criteria object to retrieve provider
        Criteria criteria = new Criteria();

        // Get the name of the best provider
        String provider = locationManager.getBestProvider(criteria, true);

        // Get Current Location
        Location myLocation = locationManager.getLastKnownLocation(provider);

        // set map type
        googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);

        // Get latitude of the current location
        latitude = myLocation.getLatitude();

        // Get longitude of the current location
        longitude = myLocation.getLongitude();

        // Create a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);
        String address = getLocationAddress(latitude, longitude);
        googleMap.addMarker(

                new MarkerOptions()
                        .position(new LatLng(latitude, longitude))
                        .title(address));
        // Show the current location in Google Map
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        // Zoom in the Google Map
        googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
    }


    public LatLng search(View v) {
        //Toast.makeText(this,"Button clicked",Toast.LENGTH_LONG).show();
        edtLocation = (EditText) findViewById(R.id.edtLocation);
        String location = edtLocation.getText().toString();
        // Toast.makeText(this, "Location " + location, Toast.LENGTH_LONG).show();
        if (location != null) {
            //Geocoder class is used to used to get Latitude and Longitude from location name & vice versa
            //  Toast.makeText(this,"If block entered",Toast.LENGTH_LONG).show();
            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);
            } catch (IOException e) {
                e.printStackTrace();
            }
            // To get address from list<Address>
            Address address = addressList.get(0);
            //String featureName = address.getFeatureName();
            String addresssLine = address.getAddressLine(0);
            String locality = address.getLocality();
            //  String subLocality = address.getSubLocality();
            String adminArea = address.getAdminArea();
            String locationAddress = addresssLine + " " + locality + " " + adminArea;
            Toast.makeText(getApplicationContext(), "Address " + locationAddress, Toast.LENGTH_LONG).show();
            //To get Latitude & Longitude
            LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
            googleMap.clear();
            //Adding marker to the specified location
            googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
            // Show the current location in Google Map
            googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            // Zoom in the Google Map
            googleMap.animateCamera(CameraUpdateFactory.zoomTo(14));
        }
        return latLng;
    }

    /*public void saveLocation(View v) {
        Toast.makeText(getApplicationContext(), "saveLocation called", Toast.LENGTH_LONG).show();
        edtLocation = (EditText) findViewById(R.id.edtLocation);
        String location_name = edtLocation.getText().toString();
        Toast.makeText(getApplicationContext(), location_name, Toast.LENGTH_LONG).show();
        SQLiteDatabase db = vibRIngDatabase.getWritableDatabase();
        ContentValues cv = new ContentValues();
        cv.put(VibRIngDatabase.LOCATION_NAME, location_name);
        long id = db.insert(VibRIngDatabase.TABLE_NAME, VibRIngDatabase.LOCATION_NAME, cv);
        Toast.makeText(getApplicationContext(), "id = " + id, Toast.LENGTH_LONG).show();
        if (id < 0)
            Toast.makeText(getApplicationContext(), "Insertion Unsuccessful", Toast.LENGTH_LONG).show();
        else
            Toast.makeText(getApplicationContext(), "Insertion Successful", Toast.LENGTH_LONG).show();
    }*/

    // Clicking the GoogleMap
    public LatLng mapClick() {
        googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng arg) {
                //Toast.makeText(getApplicationContext(), "Map Clicked", Toast.LENGTH_SHORT).show();
                // Getting the Latitude & Longitude of previously touched location
                latLng = arg;
                //Clear the previously touched position
                googleMap.clear();
                latitude = latLng.latitude;
                //Toast.makeText(getApplicationContext(),"Latitude = " +longitude,Toast.LENGTH_SHORT).show();
                longitude = latLng.longitude;
                //Toast.makeText(getApplicationContext(),"Longitude = " +longitude,Toast.LENGTH_SHORT).show();
                String name = getLocationAddress(latitude, longitude);

                //Placing the marker on the touched position
                googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));
                // Moving camera to the touched position
                googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                //Animating to touched position
                // googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
                // Zoom in the map
                googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            }
        });
        return latLng;
    }

    public String getLocationAddress(double latitude, double longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
        geocoder = new Geocoder(getApplicationContext());
        try {
            addressList = geocoder.getFromLocation(latitude, longitude, 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Address address = addressList.get(0);
        String addressLine = address.getAddressLine(0);
        //String featureName = address.getFeatureName();
        String locality = address.getLocality();
        String adminArea = address.getAdminArea();
        locationAddress = addressLine + " " + locality + " " + adminArea;
        return locationAddress;
    }

    // On clicking add button openDialog method will be called
    public void openDialog(View v) {
        Toast.makeText(getApplicationContext(), "eeeeeeeeeeeeeeeeeeeeee", Toast.LENGTH_LONG).show();
        dialogBuilder = new AlertDialog.Builder(this);
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.custom_dialog, null, false);
        dialogBuilder.setTitle("Set Mode");
        dialogBuilder.setView(view);
        AlertDialog dialog = dialogBuilder.create();
        dialog.show();
        //dialog.getWindow().setLayout(600, 800);
        TextView lat = (TextView) view.findViewById(R.id.lblLatitude);
        TextView longi = (TextView) view.findViewById(R.id.lblLongitude);
        TextView location_name = (TextView) view.findViewById(R.id.lblLocationName);
        //To retrieve the current position of the marker
        latLng = marker.getPosition();
        double lati1 = latLng.latitude;
        double longi1 = latLng.longitude;
        String name = getLocationAddress(lati1, longi1);
        Toast.makeText(getApplicationContext(), "name " + name, Toast.LENGTH_LONG).show();
        lat.setText(Double.toString(lati1));
        longi.setText(Double.toString(longi1));
        location_name.setText(name);
        RadioGroup rg = (RadioGroup) view.findViewById(R.id.modesRadioGroup);
        rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.vibrationRadioButton:
                        Toast.makeText(getApplicationContext(), "Vibration clicked", Toast.LENGTH_LONG).show();
                        break;
                    case R.id.muteRadioButton:
                        Toast.makeText(getApplicationContext(), "Mute clicked", Toast.LENGTH_LONG).show();
                        break;
                    case R.id.ringingRadioButton:
                        Toast.makeText(getApplicationContext(), "Ringing clicked", Toast.LENGTH_LONG).show();
                        break;
                    default:
                        break;
                }
            }
        });
    }


}

在此代码中,我使用的是Google Map。我的活动中有一个名为ADD的按钮。 单击ADD,调用openDialog()方法,该方法负责创建自定义对话框。这里的一切都运行正常,除了代码将给我标记的位置。单击地图后或搜索EditText后。我正在尝试使用Marker类的getPosition()方法访问当前标记位置,但它无法正常工作。

请检查openDialog()方法。

1 个答案:

答案 0 :(得分:0)

您的marker变量始终为空。您永远不会将值赋给此变量。

我不了解您应用的完整逻辑,但看起来您应该在尝试添加新标记后为marker字段指定值。例如,对于search方法,您应该更改以下行:

 googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));

marker=googleMap.addMarker(new MarkerOptions().position(latLng).title(locationAddress));

其他方法相同。 在尝试使用之前,您应该将值指定给标记。