Я изучаю карты google. Но столкнулся с проблемой, как получить местоположение определенного места через searchBar.
Вот коды: ---->
Код действия карты: - ->
package com.example.locationandmapdemo;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.nfc.Tag;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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.MarkerOptions;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[]
grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListener);
mMap.setMyLocationEnabled(true);
init();
}
}
}
}
private EditText msearchtext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
msearchtext=(EditText)findViewById(R.id.input_serach);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void init(){
Log.i("cool","init: initializing");
msearchtext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(actionId== EditorInfo.IME_ACTION_SEARCH
||actionId==EditorInfo.IME_ACTION_DONE
||event.getAction()==KeyEvent.ACTION_DOWN
||event.getAction()==KeyEvent.KEYCODE_ENTER){
geolocate();
}
return false;
}
});
}
private void geolocate(){
String searchString = msearchtext.getText().toString();
Geocoder geocoder = new Geocoder(MapsActivity.this);
List<Address> list = new ArrayList<>();
try{
list= geocoder.getFromLocationName(searchString,1);
}catch (IOException e){
e.printStackTrace();
}
if(list.size()>0){
Address address = list.get(0);
Log.i("Geolocation","geolocate:found a location:" + address.toString());
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
mMap.clear();//this will clear the map before we add something.
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try{
List<Address> listaddresses =
geocoder.getFromLocation(location.getLatitude(),location.getLongitude(),1);
if(listaddresses !=null && listaddresses.size() >0){
Log.i("placeInfo",listaddresses.get(0).toString());
String address ="";
if(listaddresses.get(0).getAdminArea() != null){
address +=listaddresses.get(0).getAdminArea() + " ";
}
if(listaddresses.get(0).getLocality() != null){
address +=listaddresses.get(0).getLocality() + " ";
}
if(listaddresses.get(0).getThoroughfare() != null){
address +=listaddresses.get(0).getThoroughfare() + " ";
}
Toast.makeText(MapsActivity.this,address,Toast.LENGTH_SHORT).show();
Log.i("Place Location",address);
}
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListener);
Location lastKnownLocation =
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
mMap.clear();
LatLng userLocation = new LatLng(lastKnownLocation.getLatitude(),
lastKnownLocation.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title("Your Location"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLocation));
}
}
}
}
Карта активности XML: ---
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<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=".MapsActivity" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_marginTop="10dp"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:elevation="10dp"
android:background="@drawable/white_border"
android:id="@+id/re1Laout1">
<ImageView
android:layout_width="15dp"
android:layout_height="15dp"
android:id="@+id/ic_magnify"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:src="@drawable/ic_magnify"
/>
<EditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/ic_magnify"
android:layout_centerVertical="true"
android:textSize="15dp"
android:textColor="#000"
android:id="@+id/input_serach"
android:background="@null"
android:hint="Enter Address, City or Zip Code"
android:imeOptions="actionSearch"/>
</RelativeLayout>
</RelativeLayout>
IN logcat, я получаю только свое текущее местоположение пользователя, но не получаю информацию о местах что я набрал в "поле поиска". предположим, что я набрал "Париж", это панель поиска. тогда она не показывает никакой информации о Париже.
В logcat нет ошибки, единственная проблема в том, что я не получение информации о местах, которые я набрал в строке поиска.
Пожалуйста, помогите
Спасибо за прочтение.