当前位置: 首页 > 知识库问答 >
问题:

Google Map Api中的PlaceAutoComplete

谷梁德容
2023-03-14

公共类MapsActivity扩展了FragmentActivity实现了OnlocReceive、OnMapReadyCallback、GoogleMap.OnMapClickListener、/*LocationListener、/GoogleMap.OnMarkerClickListener/、GooglePiclient.OnConnectionFailedListener、GooglePiclient.ConnectionCallbacks*/{

private GoogleMap mMap;

Marker m;

public static final String TAG = MapsActivity.class.getSimpleName();

private GoogleApiClient mGoogleApiClient;

private LocationRequest mLocationRequest;

Location location;

int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;

private final int MY_PERMISSIONS_REQUEST_CODE = 1;

private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

public GoogleApiClient getmGoogleApiClient()
{
    return mGoogleApiClient;
}

boolean bound = false;

LocationUpdateService locationService;


public ServiceConnection serviceConnection;

Intent serviceIntent;

PlaceAutocompleteFragment autocompleteFragment;

AutocompleteFilter typeFilter;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.newlayout);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

   autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);



    typeFilter = new AutocompleteFilter.Builder().setTypeFilter(AutocompleteFilter.TYPE_FILTER_ADDRESS).build();

    autocompleteFragment.setFilter(typeFilter);

    autocompleteFragment.setBoundsBias(new LatLngBounds(
            new LatLng(-33.880490, 151.184363),
            new LatLng(-33.858754, 151.229596)));



    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {

            // TODO: Get info about the selected place.
            Log.i(TAG, "Place: ------------------------>" + place.getName());


            Toast.makeText(MapsActivity.this, "place:"+place.getName(), Toast.LENGTH_SHORT).show();

            PendingResult<AutocompletePredictionBuffer> result =
                    Places.GeoDataApi.getAutocompletePredictions(mGoogleApiClient,place.getName().toString(),
                            null, typeFilter);


        }

        @Override
        public void onError(Status status) {

        }
    });

    ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    if (!mWifi.isConnected()) {
        builALertMessageNoWifi();
    }


    final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );

    if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
        buildAlertMessageNoGps();



    }

    serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {

            locationService = ((LocationUpdateService.localBinder)service).getservice();

            locationService.passClassrefrence(MapsActivity.this);



            Toast.makeText(MapsActivity.this, "bound", Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

            bound = false;

            Toast.makeText(MapsActivity.this, "not_bound", Toast.LENGTH_SHORT).show();

        }
    };




    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
    {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Toast.makeText(MapsActivity.this, "req permission", Toast.LENGTH_SHORT).show();
            requestPermissions(new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_CODE);

        }





    }
    else
    {
        // location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        serviceIntent = new Intent(MapsActivity.this,LocationUpdateService.class);
        startService(serviceIntent);

        bound= bindService(serviceIntent,serviceConnection,BIND_AUTO_CREATE);
    }

public void onMapReady(GoogleMap GoogleMap){mMap=GoogleMap;

    Toast.makeText(MapsActivity.this, "onMapReady", Toast.LENGTH_SHORT).show();

    mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);

}

private void handleNewLocation(Location location) {

    Log.i(TAG, "in handle new location---------------------->.");


    Log.d(TAG, location.toString());

    double currentLatitude = location.getLatitude();
    double currentLongitude = location.getLongitude();

    Toast.makeText(MapsActivity.this, "lat:"+currentLatitude+"  lang:"+currentLongitude, Toast.LENGTH_SHORT).show();

    LatLng latLng = new LatLng(currentLatitude, currentLongitude);

    //mMap.addMarker(new MarkerOptions().position(new LatLng(currentLatitude, currentLongitude)).title("Current Location"));
    MarkerOptions options = new MarkerOptions()
            .position(latLng)
            .title("I am here!");
    if(m!=null)
        m.remove();

  m =  mMap.addMarker(options);
   // mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 17));

}

@Override
public void onreceive(Location l) {
    handleNewLocation(l);


    if(serviceIntent!=null && bound==true ) {


        locationService.stopupdates();
        stopService(serviceIntent);


        Toast.makeText(MapsActivity.this, "stop service", Toast.LENGTH_SHORT).show();
    }

}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);


    if (requestCode == MY_PERMISSIONS_REQUEST_CODE) {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED)

        {
            Toast.makeText(MapsActivity.this, " granted " + grantResults[0] + "granted2" + grantResults[1], Toast.LENGTH_SHORT).show();

            try {
              //  location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);


                Toast.makeText(MapsActivity.this, "in recieve request new location", Toast.LENGTH_SHORT).show();
                serviceIntent = new Intent(MapsActivity.this,LocationUpdateService.class);
                startService(serviceIntent);
                bound =  bindService(serviceIntent,serviceConnection,BIND_AUTO_CREATE);

            } catch (SecurityException e) {

            }
   }


    }
}

@Override
protected void onResume() {

    Toast.makeText(MapsActivity.this, "on Resume", Toast.LENGTH_SHORT).show();

  //  stopService(serviceIntent);

    super.onResume();

}

@Override
protected void onDestroy() {


    if(serviceIntent!=null && bound ==true ) {
        locationService.stopupdates();
        stopService(serviceIntent);

       // unbindService(serviceConnection);

    }
    super.onDestroy();

}

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                public void onClick(@SuppressWarnings("unused") final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                }
            })
            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                public void onClick(final DialogInterface dialog, @SuppressWarnings("unused") final int id) {
                    dialog.cancel();
                }
            });
    final AlertDialog alert = builder.create();
    alert.show();
}

private void builALertMessageNoWifi()
{
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Your WIFI seeems to be disabled, do you want to enable it?")
            .setCancelable(false)
            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));

                }
            })

            .setNegativeButton("No", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });

    final AlertDialog alert = builder.create();
    alert.show();

}

}

暂时还没有答案

 类似资料:
  • 我使用子JPanel构造JScrollPane,然后尝试将JScrollPane添加到父JPanel中,希望有一个可滚动的自定义JPanel。 我有一个大的细白线前面的所有我的组件,他们是没有滚动。有什么想法吗?

  • 我已经为android Studio创建了一个webview应用程序。但没有加载web URL。错误为NET::ERR_ACCESS_DENIED。有谁能帮忙吗

  • 我有一个使用Java Version8的Spring和Maven的项目。当我运行maven update时,它适用于Java9或更高版本,当我编译它时,它适用于Java8。我注意到了这一点,因为用Maven更新会将一个特定的类更改为Java9,而我无法导入这个类。 这个类是:javax.annotation.generated(Java8)。 这是要导入的类。但是,当我进行maven更新时,文件的

  • 当应用程序启动EncryptionBootstrapConfiguration无法自动装配我的自定义TextEncryptor-https://github.com/spring-cloud/spring-cloud-commons/blob/cde7c7f3118382490c28776f66e0a56f248141fd/spring-cloud-context/src/main/java/or

  • 我有一个问题,找出我的源代码中的错误。 有什么办法可以解决它吗? 我的代码中抛出了“ArrayIndexOutOfBoundsException”,但我无法找到它的位置。 android studio中的logcat:

  • RISC-V 与中断相关的寄存器和指令 [info] 回顾:RISC-V 中的机器态(Machine Mode,机器模式,M 模式) 是 RISC-V 中的最高权限模式,一些底层操作的指令只能由机器态进行使用。 是所有标准 RISC-V 处理器都必须实现的模式。 默认所有中断实际上是交给机器态处理的,但是为了实现更多功能,机器态会将某些中断交由内核态处理。这些异常也正是我们编写操作系统所需要实现的