gpt4 book ai didi

android - 无法使用谷歌地图获取 map

转载 作者:行者123 更新时间:2023-11-29 19:38:29 25 4
gpt4 key购买 nike

我没有使用 Google Places API 和 Google Map API V2 获取谷歌地图。我正在显示我正在使用的所有代码,因为无法解决错误。

我想使用 Google Places API 和 Google Map Android API V2 显示附近的地点。

我在这一行中遇到错误:

// Getting Google Map
mGoogleMap = fragment.getMap();

错误是无法解析getMap();

Note: C:\Users\techaboard user\Downloads\LocationNearby9\app\src\main\java\neerajshah\locationnearby\MainActivity.java uses or overrides a deprecated API.
Error:(106, 34) error: cannot find symbol method getMap()

主 Activity .java

public class MainActivity extends FragmentActivity implements LocationListener,OnMapReadyCallback {

GoogleMap mGoogleMap;
Spinner mSprPlaceType;

String[] mPlaceType = null;
String[] mPlaceTypeName = null;

double mLatitude = 0;
double mLongitude = 0;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Array of place types
mPlaceType = getResources().getStringArray(R.array.place_type);

// Array of place type names
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);

// Creating an array adapter with an array of Place types
// to populate the spinner
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);

// Getting reference to the Spinner
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);

// Setting adapter on Spinner to set place types
mSprPlaceType.setAdapter(adapter);

Button btnFind;

// Getting reference to Find Button
btnFind = (Button) findViewById(R.id.btn_find);

// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available

int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();

} else { // Google Play Services are available

// Getting reference to the SupportMapFragment


SupportMapFragment fragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map));

// Getting Google Map
//setUpMapIfNeeded();
fragment.getMapAsyn‌​c(this);
// onMapReady(GoogleMa‌​p googleMap);
//mGoogleMap = fragment.getMap();
// Enabling MyLocation in Google Map
mGoogleMap.setMyLocationEnabled(true);

// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

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

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

// Getting Current Location From GPS
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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(provider);

if (location != null) {
onLocationChanged(location);
}

locationManager.requestLocationUpdates(provider, 20000, 0, this);

// Setting click event lister for the find button
btnFind.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {

int selectedPosition = mSprPlaceType.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];

StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + mLatitude + "," + mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyCl0SmU1xPrcR_f_VG-PoGWpDYY9qagTcE");

// Creating a new non-ui thread task to download json data
PlacesTask placesTask = new PlacesTask();

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

}
});

}

// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
/**
* 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;
}



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

// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://neerajshah.locationnearby/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}

@Override
public void onStop() {
super.onStop();

// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://neerajshah.locationnearby/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
@Override
public void onMapReady(GoogleMap googleMap) {
GoogleMap map;
map = googleMap;

map.getUiSettings().setMapToolbarEnabled(false);
// map.getUiSettings().setMyLocationButtonEnabled(false);
//map.getUiSettings().setZoomControlsEnabled(false);
//etc...
}

@Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);

mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));

}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}


/**
* A class, to download Google Places
*/
class PlacesTask extends AsyncTask<String, Integer, String> {

String data = null;

// Invoked by execute() method of this object
@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) {
ParserTask parserTask = new ParserTask();

// 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
*/
class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {

JSONObject jObject;

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

List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();

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

/** Getting the parsed data as a List construct */
places = placeJsonParser.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, String>> list) {

// Clears all the existing markers


GoogleMap mGoogleMap =null;
mGoogleMap.clear();

for (int i = 0; i < list.size(); i++) {

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

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

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

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

// Getting name
String name = hmPlace.get("place_name");

// Getting vicinity
String vicinity = hmPlace.get("vicinity");

LatLng latLng = new LatLng(lat, lng);

// Setting the position for the marker
markerOptions.position(latLng);

// Setting the title for the marker.
//This will be displayed on taping the marker
markerOptions.title(name + " : " + vicinity);

// Placing a marker on the touched position

mGoogleMap.addMarker(markerOptions);
}
}
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >

<Spinner
android:id="@+id/spr_place_type"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentTop="true" />

<Button
android:id="@+id/btn_find"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:layout_alignParentTop="true"
android:layout_toRightOf="@id/spr_place_type"
android:text="@string/str_btn_find" />



<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/map"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/spr_place_type"
class="com.google.android.gms.maps.SupportMapFragment" />

</RelativeLayout>

日志

   FATAL EXCEPTION: main
Process: neerajshah.locationnearby, PID: 7764
java.lang.RuntimeException: Unable to start activity ComponentInfo{neerajshah.locationnearby/neerajshah.locationnearby.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
at android.app.ActivityThread.access$900(ActivityThread.java:154)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(boolean)' on a null object reference
at neerajshah.locationnearby.MainActivity.onCreate(MainActivity.java:111)
at android.app.Activity.performCreate(Activity.java:6259)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
at android.app.ActivityThread.access$900(ActivityThread.java:154) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5443) 

最佳答案

在 XML 中添加它。

 <fragment
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />

并尝试在 Java 文件中使用它

private GoogleMap map;
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the
// map.
if (map == null) {

map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

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) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
map.getUiSettings().setMyLocationButtonEnabled(false);
map.getUiSettings().setZoomControlsEnabled(false);
map.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
@Override
public void onMyLocationChange(Location loc) {

}
});
}

}

关于android - 无法使用谷歌地图获取 map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38967881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com