程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了使用 Google Maps API 从当前位置获取附近地点的结果大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决使用 Google Maps API 从当前位置获取附近地点的结果?

开发过程中遇到使用 Google Maps API 从当前位置获取附近地点的结果的问题如何解决?下面主要结合日常开发的经验,给出你关于使用 Google Maps API 从当前位置获取附近地点的结果的解决方法建议,希望对你解决使用 Google Maps API 从当前位置获取附近地点的结果有所启发或帮助;

这是我的代码:

public class MapsActivity extends AppCompatActivity implements OnMapReadyCallBACk,LOCATIOnListener,Googleapiclient.ConnectionCallBACks,Googleapiclient.onConnectionFailedListener {

GoogleMap mMap;
SupportMapFragment mapFragment;
LOCATIOnrequest mLOCATIOnrequest;
Googleapiclient clIEnt;
LOCATIOn mLastLOCATIOn;
Marker mCurrLOCATIOnMarker;
LatLng latLongCurrent;

@OverrIDe
protected voID onCreate(Bundle savedInstanceStatE) {
    super.onCreate(savedInstanceStatE);

    setContentVIEw(R.layout.activity_map);

    getSupportActionbar().settitle("Map LOCATIOn");
    // Obtain the SupportMapFragment and get notifIEd when the map is ready to be used.
    mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentByID(R.ID.map);
    mapFragment.getMapAsync(this);

}

public voID findRestaurant(View view) {
    StringBuilder StringBuilder = new StringBuilder("https://maps.GoogleAPIs.com/maps/API/place/nearbysearch/Json?");
    StringBuilder.append("LOCATIOn=" + latLongCurrent.latitude + "," + latLongCurrent.longitudE); //error attempt to read from fIEld 'double...on a null object reference
    StringBuilder.append("&radius=" + 1000);
    StringBuilder.append("&keyword=" + "restaurant");
    StringBuilder.append("&key=" + getresources().getString(R.String.Google_places_key));

    String url = StringBuilder.toString();

    Object dataTransfer[] = new Object[2];
    dataTransfer[0] = mMap;
    dataTransfer[1] = url;

    NearbySearch nearbySearch = new NearbySearch(this);
    nearbySearch.execute(dataTransfer);
}

@OverrIDe
public voID onPause() {
    super.onPause();

    //stop LOCATIOn updates when Activity is no longer active
    if (clIEnt != null) {
        LOCATIOnservices.FusedLOCATIOnAPI.removeLOCATIOnupdates(clIEnt,this);
    }
}

@OverrIDe
public Boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.map_options,menu);
    return true;
}

@OverrIDe
public voID onMapReady(GoogleMap GoogleMap) {
    mMap = GoogleMap;
    //Initializing the Google Play services
    if (androID.os.build.VERSION.SDK_INT >= Build.VERSION_CODEs.M) {
        if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            //LOCATIOn Permission already granted
            buildGoogleapiclient();
            mMap.setMyLOCATIOnEnabled(true);
        } else {
            //request LOCATIOn Permission
            checkLOCATIOnPermission();
        }
    } else {
        buildGoogleapiclient();
        mMap.setMyLOCATIOnEnabled(true);
    }
}

protected synchronized voID buildGoogleapiclient() {
    clIEnt = new Googleapiclient.builder(this)
            .addConnectionCallBACks(this)
            .addOnConnectionFailedListener(this)
            .addAPI(LOCATIOnservices.API)
            .build();
    clIEnt.connect();
}

@OverrIDe
public voID onConnected(Bundle bundlE) {
    mLOCATIOnrequest = new LOCATIOnrequest();
    mLOCATIOnrequest.seTinterval(1000);
    mLOCATIOnrequest.setFastesTinterval(1000);
    mLOCATIOnrequest.setPriority(LOCATIOnrequest.PRIORITY_BALANCED_POWER_ACCURACY);
    if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {
        LOCATIOnservices.FusedLOCATIOnAPI.requestLOCATIOnupdates(clIEnt,mLOCATIOnrequest,this);
    }
}

@OverrIDe
public Boolean onoptionsItemSELEcted(MenuItem item) {
    // Change the map type based on the user's SELEction.
    switch (item.getItemID()) {
        case R.ID.normal_map:
            mMap.setMapType(GoogleMap.MAP_TYPE_norMAL);
            return true;
        case R.ID.hybrID_map:
            mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
            return true;
        case R.ID.satellite_map:
            mMap.setMapType(GoogleMap.MAP_TYPE_SATELliTE);
            return true;
        case R.ID.terrain_map:
            mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
            return true;
        default:
            return super.onoptionsItemSELEcted(item);
    }
}

@OverrIDe
public voID onLOCATIOnChanged(LOCATIOn LOCATIOn) {
    mLastLOCATIOn = LOCATIOn;
    if (mCurrLOCATIOnMarker != null) {
        mCurrLOCATIOnMarker.remove();
    }

    //Place current LOCATIOn marker
    LatLng latLng = new LatLng(LOCATIOn.getLatitude(),LOCATIOn.getLongitude());

    MarkerOptions markerOptions = new MarkerOptions();
    markerOptions.position(latLng);
    markerOptions.title("My current position");
    
    mCurrLOCATIOnMarker = mMap.addMarker(markerOptions);
}

public static final int MY_PERMISSIONS_requEST_LOCATION = 99;

private voID checkLOCATIOnPermission() {
    if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

        if (ActivityCompat.shouldShowrequestPermissionRationale(this,Manifest.permission.ACCESS_FINE_LOCATION)) {

            new AlertDialog.builder(MapsActivity.this)
                    .settitle("LOCATIOn Permission Needed")
                    .setmessage("This app needs the LOCATIOn permission,please accept this to use the LOCATIOn functionality")
                    .setPositivebutton("OK",new DialogInterface.onClickListener() {
                        @OverrIDe
                        public voID onClick(DialogInterface dialogInterface,int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(MapsActivity.this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},MY_PERMISSIONS_requEST_LOCATION);
                        }
                    }).create().show();

        } else {
            // No explanation needed,we can request the permission.
            ActivityCompat.requestPermissions(this,MY_PERMISSIONS_requEST_LOCATION);
        }
    }
}

@OverrIDe
public voID onrequestPermissionsResult(int requestCode,String permissions[],int[] grantResults) {
    super.onrequestPermissionsResult(requestCode,permissions,grantResults);
    switch (requestCodE) {
        case MY_PERMISSIONS_requEST_LOCATION: {
            // If request is cancelled,the result arrays are empty.
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                if (ContextCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    if (clIEnt == null) {
                        buildGoogleapiclient();
                    }
                    mMap.setMyLOCATIOnEnabled(true);
                }

            } else {

                Toast.makeText(this,"Permission is denIEd",Toast.LENGTH_LONG).show();
            }
            return;
        }

    }
}

private voID moveCamera(LatLng latLang,float zoom,String titlE) {
    mMap.moveCamera(CameraupdateFactory.newLatLngZoom(latLang,zoom));

    //wriTing the code to drop the pin or marker
    MarkerOptions options = new MarkerOptions().position(latLang).title(titlE);
    mMap.addMarker(options);
}


@OverrIDe
public voID onConnectionSuspended(int i) {

}

@OverrIDe
public voID onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

}

这是我的类 NearbySearch.java 代码如下:

public class NearbySearch extends AsyncTask<Object,String,String> {
GoogleMap mMap;
String url;
inputStream is;
BufferedReader bufferedReader;
StringBuilder StringBuilder;
String data;

public NearbySearch(MapsActivity mapsActivity) {
}

@OverrIDe
protected String doInBACkground(Object... objects) {

    //requesTing for the response from the Google places API
    mMap = (GoogleMap) objects[0];
    try {
        URL myUrl = new URL(url);
        httpURLConnection httpURLConnection = (httpURLConnection) myUrl.openConnection();
        is = httpURLConnection.geTinputStream();
        bufferedReader = new BufferedReader(new inputStreamReader(is));

        String line = "";
        StringBuilder = new StringBuilder();

        while ((line = bufferedReader.readline()) != null) {

            StringBuilder.append(linE);
        }

        //Receiving the data from Json
        data = StringBuilder.toString();

    } catch (MalformedURLException E) {
        e.printstacktrace();
    } catch (IOException E) {
        e.printstacktrace();
    }
    return data;
}

@OverrIDe
protected voID onPostExecute(String s) {

    try {
        JsONObject parentObject = new JsONObject(s);
        JsONArray resultArray = parentObject.getJsONArray("results");

        for (int i = 0; i < resultArray.length(); i++) {
            JsONObject JsonObject = resultArray.getJsONObject(i);
            JsONObject LOCATIOnObject = JsonObject.getJsONObject("geometry").getJsONObject("LOCATIOn");

            String latitude = JsonObject.getString("lat");
            String longitude = JsonObject.getString("lng");

            JsONObject nameObject = resultArray.getJsONObject(i);

            String nameRestaurant = nameObject.getString("name");
            String vicinity = nameObject.getString("vicinity");

            LatLng latLng = new LatLng(Double.parseDouble(latitudE),Double.parseDouble(longitudE));

            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.title(vicinity);
            markerOptions.position(latLng);

            mMap.addMarker(markerOptions);
        }
    } catch (JsONException E) {
        e.printstacktrace();
    }
    super.onPostExecute(s);
}
}

我已成功获取用户的当前位置,但无法找到从当前位置查找附近餐馆的解决方案。请帮助摆脱它,因为我在这里被困了 2 天。请告诉我是否还有其他解决方案。谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

大佬总结

以上是大佬教程为你收集整理的使用 Google Maps API 从当前位置获取附近地点的结果全部内容,希望文章能够帮你解决使用 Google Maps API 从当前位置获取附近地点的结果所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。