没有从地图获取位置

时间:2016-04-24 06:52:10

标签: java android google-maps

我正在制作基于位置的提醒应用程序...但是当我点击特定位置然后标记添加到此位置但是当我点击提交时它不会显示所选位置..它只获得我当前的经度和纬度。 ..我的代码......

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_to_map);
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);


    this.mainClass = (MainClass) getApplication();
    this.drawablered = getResources().getDrawable(R.mipmap.mainpin);
    final Drawable buttonSelector = getResources().getDrawable(R.drawable.buttonselector);
    this.buttonSubmit = (Button) findViewById(R.id.buttonSubmit);
    this.buttonShowSearch = (Button) findViewById(R.id.buttonShowSearch);

    this.locationTextView = new AutoCompleteTextView(getApplicationContext());
    this.buttonSearch = new Button(getApplicationContext());
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    height = displaymetrics.heightPixels;
    this.width = displaymetrics.widthPixels;
    density = displaymetrics.densityDpi;
    this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    boolean available = false;
    NetworkInfo netInfo = ((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        available = true;
    }
    if (!available) {
        this.mainClass.setLongToast("Sorry, there is not network connection to display the map");
    }
    try {
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            int hasReadContactPermission = checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION);
            if (hasReadContactPermission != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                        124);
                return;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);

    Log.d("GPS Enabled", "GPS Enabled");
    if (this.locationManager != null) {
        this.currentLocation = this.locationManager.getLastKnownLocation("gps");
        if (this.currentLocation != null) {
            this.currentLatitude = Double.valueOf(this.currentLocation.getLatitude());
            this.currentLongitude = Double.valueOf(this.currentLocation.getLongitude());
            this.currentPoint = new LatLng((int) (this.currentLatitude.doubleValue() * 1000000.0d), (int) (this.currentLongitude.doubleValue() * 1000000.0d));
            locationLat = this.currentLatitude.doubleValue();
            locationLong = this.currentLongitude.doubleValue();
        } else {

        }
    } else {

    }

    this.buttonShowSearch.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            AddLocationActivity.this.linearLayout = (LinearLayout) AddLocationActivity.this.findViewById(R.id.layout_search);
            AddLocationActivity.this.locationTextView.setHint("Location to search");
            //AddLocationActivity.this.locationTextView.setTextColor(getColor(R.color.colorAccent));
            AddLocationActivity.this.locationTextView.setWidth((AddLocationActivity.this.width / 4) * 3);
            AddLocationActivity.this.locationTextView.setHeight(36);
            AddLocationActivity.this.buttonSearch.setWidth(AddLocationActivity.this.width * 0);
            AddLocationActivity.this.buttonSearch.setHeight(40);
            AddLocationActivity.this.buttonSearch.setBackgroundDrawable(buttonSelector);
            AddLocationActivity.this.buttonSearch.setText("Search");
            AddLocationActivity.this.buttonSearch.setTextColor(-1);
            AddLocationActivity.this.linearLayout.setOrientation(LinearLayout.VERTICAL);
            AddLocationActivity.this.linearLayout.setVerticalGravity(16);
            AddLocationActivity.this.linearLayout.addView(AddLocationActivity.this.locationTextView);
            AddLocationActivity.this.linearLayout.addView(AddLocationActivity.this.buttonSearch);
            AddLocationActivity.this.buttonShowSearch.setEnabled(false);
        }
    });
    this.buttonSearch.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            AddLocationActivity.this.location = AddLocationActivity.this.locationTextView.getText().toString();
            AddLocationActivity.this.location.trim();
            if (AddLocationActivity.this.location.compareTo("") != 0) {
                AddLocationActivity.this.searchLocation();
                AddLocationActivity.this.linearLayout.removeAllViews();
                return;
            }
            AddLocationActivity.this.mainClass.setLongToast("Please enter a location");
        }
    });
    this.buttonSubmit.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            if (AddLocationActivity.locationLat == 0.0d || AddLocationActivity.locationLong == 0.0d) {
                AddLocationActivity.this.mainClass.setLongToast("Sorry, failed to submit");
                return;
            }
            AddLocationActivity.this.mainClass.latitude = new StringBuilder(String.valueOf(AddLocationActivity.locationLat)).toString();
            AddLocationActivity.this.mainClass.longitude = new StringBuilder(String.valueOf(AddLocationActivity.locationLong)).toString();
            AddLocationActivity.this.mainClass.locationName = AddLocationActivity.locationName;
            AddLocationActivity.this.finish();
        }
    });
}


protected void onResume() {
    super.onResume();
    this.mainClass.favListFlag = false;

}

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_home_screen, menu);
    return true;
}

public boolean onOptionsItemSelected(MenuItem item) {
    return this.mainClass.menuItemClick(item, getBaseContext());
}

protected boolean isRouteDisplayed() {
    return false;
}

public void onLocationChanged(Location location) {
}

public void onProviderDisabled(String provider) {
}

public void onProviderEnabled(String provider) {
}

public void onStatusChanged(String provider, int status, Bundle extras) {
}

private void searchLocation() {
    final Handler Modelhandler = new Handler() {
        public void handleMessage(Message msg) {
            AddLocationActivity.this.buttonShowSearch.setEnabled(true);
            if (msg.obj == "1") {
                AddLocationActivity.this.locationTextView.setText("");
                AddLocationActivity.this.mainClass.setLongToast("Sorry, this location could not be marked, please mark the point manually");
            } else if (msg.obj == "2") {
                AddLocationActivity.this.addMarker(AddLocationActivity.this.point, AddLocationActivity.locationName);
            }
        }
    };
    new Thread() {
        public void run() {
            StringBuilder stringBuilder;
            Message msg = new Message();
            try {
                ((InputMethodManager) AddLocationActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AddLocationActivity.this.getCurrentFocus().getWindowToken(), 0);
            } catch (Exception e) {
            }
            String str = "";
            for (int i = 0; i < AddLocationActivity.this.location.length(); i++) {
                if (AddLocationActivity.this.location.substring(i, i + 1).equalsIgnoreCase(" ")) {
                    str = new StringBuilder(String.valueOf(str)).append("+").toString();
                } else {
                    str = new StringBuilder(String.valueOf(str)).append(AddLocationActivity.this.location.substring(i, i + 1)).toString();
                }
            }
            if (str.compareTo("") != 0) {
                AddLocationActivity.this.location = str;
            }

            URL url;
            HttpURLConnection connection = null;
            String responseStr = "";
            try {


                url = new URL("http://maps.google.com/maps/api/geocode/json?address=" + AddLocationActivity.this.location + "ka&sensor=false");

                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                connection.setUseCaches(false);
                connection.setDoInput(true);
                connection.setDoOutput(false);

                DataOutputStream wr = new
                        DataOutputStream(connection.getOutputStream());

                wr.flush();
                wr.close();
                // Get Response
                int status = connection.getResponseCode();
                BufferedInputStream in;
                if (status >= 400) {
                    in = new BufferedInputStream(connection.getErrorStream());
                } else {
                    in = new BufferedInputStream(connection.getInputStream());
                }

                BufferedReader rd = new BufferedReader(new InputStreamReader(in));
                String line;
                StringBuffer response = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
                rd.close();
                responseStr = response.toString();
                Log.d("Server response", responseStr);

            } catch (Exception e) {

                e.printStackTrace();


            } finally {

                if (connection != null) {
                    connection.disconnect();
                }

            }


            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject = new JSONObject(responseStr);
            } catch (JSONException e4) {
                e4.printStackTrace();
            }
            Double d = new Double(0.0d);
            d = new Double(0.0d);
            Double lon1 = 0.0, lat1 = 0.0;
            try {
                lon1 = Double.valueOf(((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng"));
                lat1 = Double.valueOf(((JSONArray) jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat"));
            } catch (JSONException e42) {
                e42.printStackTrace();
            }
            if (lon1.doubleValue() == 0.0d && lat1.doubleValue() == 0.0d) {
                msg.obj = "1";
            } else {
                AddLocationActivity.this.point = new LatLng((int) (lat1.doubleValue() * 1000000.0d), (int) (lon1.doubleValue() * 1000000.0d));
                Geocoder geocoder = new Geocoder(AddLocationActivity.this.getApplicationContext(), Locale.getDefault());
                try {
                    StringBuilder _homeAddress = new StringBuilder();
                    try {
                        List<Address> addresses = geocoder.getFromLocation(lat1.doubleValue(), lon1.doubleValue(), 1);
                        for (int index = 0; index < addresses.size(); index++) {
                            Address address = (Address) addresses.get(index);
                            AddLocationActivity.locationLat = lat1.doubleValue();
                            AddLocationActivity.locationLong = lon1.doubleValue();
                            if (address.getLocality() == null) {
                                AddLocationActivity.locationName = address.getAddressLine(0);
                            } else {
                                AddLocationActivity.locationName = address.getAddressLine(0) + ", " + address.getLocality();
                            }
                        }
                        stringBuilder = _homeAddress;
                    } catch (Exception e5) {
                        stringBuilder = _homeAddress;
                    }
                } catch (Exception e6) {
                }
                msg.obj = "2";
            }
            Modelhandler.sendMessage(msg);
        }
    }.start();
}

private void addMarker(LatLng point, String locationName) {
    if (mMap != null) {
        mMap.clear();
        mMap.moveCamera(CameraUpdateFactory.newLatLng(point));

        this.itemizedoverlay = new MapItemizedOverlay(this.drawablered, getApplicationContext());

        this.itemizedoverlay.addOverlay(this.overlayitem);
        this.mapOverlays.add(this.itemizedoverlay);
        this.mv.invalidate();
        if (!locationName.equals("")) {
            View map_popup = ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.map_popup, null);
            ((TextView) map_popup.findViewById(R.id.textViewLocName)).setText(locationName);
            this.mainClass.toast = new Toast(getApplicationContext());
            this.mainClass.toast.setDuration(Toast.LENGTH_LONG);
            this.mainClass.toast.setGravity(48, 0, ((height / 2) - (height / 10)) - 60);
            this.mainClass.toast.setView(map_popup);
            this.mainClass.toast.show();
        }
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    //this.mMap = googleMap;
    LatLng sydney = new LatLng(-34.0d, 151.0d);
    this.mMap.addMarker(new MarkerOptions().position(sydney).title("Sydney"));
    this.mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(sydney, 10.0f));
    this.mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        public void onMapClick(LatLng latLng) {
            AddLocationActivity.this.mMap.clear();
            AddLocationActivity.locationLat = latLng.latitude;
            AddLocationActivity.locationLong = latLng.longitude;
            AddLocationActivity.this.mMap.addMarker(new MarkerOptions().position(new LatLng(AddLocationActivity.locationLat, AddLocationActivity.locationLong)).title(BuildConfig.FLAVOR + AddLocationActivity.locationLat + "\n" + AddLocationActivity.locationLong));
            AddLocationActivity.this.mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(AddLocationActivity.locationLat, AddLocationActivity.locationLong), 10.9f));

        }
    });
}

}

0 个答案:

没有答案