简体   繁体   English

如何获取经度和纬度并将其放入JSON链接?

[英]How Can I get Longitude and Latitude and put it into JSON link?

I've been trying to grab longitude and latitude with LocationListener and casting it as an int to put into a JSON link so I can use the data from current user location. 我一直在尝试使用LocationListener捕获经度和纬度,并将其强制转换为int以放入JSON链接,以便可以使用当前用户位置的数据。 My app crashes when I try to start it but I can get the longitude and latitude coordinates. 尝试启动它时,我的应用程序崩溃了,但是我可以获取经度和纬度坐标。 I've broken my app down to just simply being able to grab the longitude and latitude from one activity and trying to get those values in another activity where I will put my JSON activity. 我已经将我的应用程序分解为仅仅能够从一个活动中获取经度和纬度,并试图在另一个活动中获取这些值,然后将我的JSON活动放入其中。 Is there something I'm missing? 有什么我想念的吗?


MANIFEST 表现

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="viaan.carl.mytest" >

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

MAIN ACTIVITY 主要活动

import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;

import android.view.Menu;

import android.widget.Toast;


public class MainActivity extends Activity implements LocationListener {

LocationManager locationmanager;
myGPS gps = new myGPS(this);


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    locationmanager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
    Criteria cri=new Criteria();
    String provider=locationmanager.getBestProvider(cri,false);

    if(provider!=null & !provider.equals(""))
    {
        Location location=locationmanager.getLastKnownLocation(provider);
        locationmanager.requestLocationUpdates(provider,2000,1,this);
        if(location!=null)
        {
            onLocationChanged(location);
        }
        else{
            Toast.makeText(getApplicationContext(),"location not found",Toast.LENGTH_LONG ).show();
        }
    }
    else
    {
        Toast.makeText(getApplicationContext(),"Provider is null",Toast.LENGTH_LONG).show();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}
@Override
public void onLocationChanged(Location location) {

    int lat;
    gps.setLat((int) location.getLatitude());
    int lng;
    gps.setLng((int) location.getLongitude());

    //TextView textView2=(TextView)findViewById(R.id.textview2);

    //TextView textView3=(TextView)findViewById(R.id.textview3);

    //textView2.setText("Latitude"+location.getLatitude());
    //textView3.setText("Longitude" + location.getLongitude());

}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}

}

Getter & Setter Class 吸气与塞特课程

import android.app.Activity;
import android.content.SharedPreferences;

public class myGPS {

private int lat;
private int lng;
SharedPreferences prefs;

public myGPS(Activity activity) {
    prefs = activity.getPreferences(Activity.MODE_PRIVATE);
}


void setLng(int lng) {
    this.lng = lng;
}

int getLat() {
    return lat;
}

int getLng() {
    return lng;
}

void setLat(int lat) {
    this.lat = lat;
}
}

New Class where JSON will be (currently just trying to display the data) JSON将使用的新类(当前仅尝试显示数据)

import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class LocationDisplay extends Fragment {

TextView textView2;
TextView textView3;

myGPS gps;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_wind, container, false);
    textView2 = (TextView)rootView.findViewById(R.id.textview2);
    textView3 = (TextView)rootView.findViewById(R.id.textview3);

    return rootView;
}

public LocationDisplay () {
    textView2.setText("Latitude: " + gps.getLat());
    textView3.setText("Longitude: " + gps.getLng());
}
}

LogCat logcat的

06-05 11:36:52.499    1943-1943/? D/dalvikvm﹕ Late-enabling CheckJNI
06-05 11:36:52.567    1943-1943/viaan.carl.mytest E/Trace﹕ error opening trace file: No such file or directory (2)
06-05 11:36:52.575    1943-1943/viaan.carl.mytest D/AndroidRuntime﹕ Shutting down VM
06-05 11:36:52.575    1943-1943/viaan.carl.mytest W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0xa619f908)
06-05 11:36:52.583    1943-1943/viaan.carl.mytest E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{viaan.carl.mytest/viaan.carl.mytest.MainActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
        at android.app.ActivityThread.access$600(ActivityThread.java:141)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:5041)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.NullPointerException
        at android.content.ContextWrapper.getPackageName(ContextWrapper.java:135)
        at android.app.Activity.getLocalClassName(Activity.java:4415)
        at android.app.Activity.getPreferences(Activity.java:4449)
        at viaan.carl.mytest.myGPS.<init>(myGPS.java:16)
        at viaan.carl.mytest.MainActivity.<init>(MainActivity.java:29)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1319)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)

You are getting the Location the old way. 您以旧方式获取Location Google released new Places API this IO. Google为此IO发布了新的Places API You can also get the current location on Android of the user the following way: 您还可以通过以下方式获取用户在Android上的当前位置

PendingResult<PlaceLikelihoodBuffer> result = Places.PlaceDetectionApi
    .getCurrentPlace(mGoogleApiClient, null);
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() {
  @Override
  public void onResult(PlaceLikelihoodBuffer likelyPlaces) {
    for (PlaceLikelihood placeLikelihood : likelyPlaces) {
      // this is your Location
      Log.i(TAG, String.format("Place '%s' has likelihood: %g",
          placeLikelihood.getPlace().getName(),
          placeLikelihood.getLikelihood()));
    }
    likelyPlaces.release();
  }
});

You do not have to make an API call if you want the current location. 如果需要当前位置,则不必进行API调用。 Here is how you can get started . 这是您的入门方法 You can get latitude/longitude from the Location object. 您可以从“ 位置”对象获取经度/纬度。

double latitude = location.getLatitude();
double longitude = location.getLongitude();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM