2016-10-19 12 views
1

Я новичок в андроиде, и я создаю приложение, которое рассчитает базу расстояния от начальной широты и долготы до текущей широты и долготы. Ниже мой код на расстоянии от широты и долготы, где начало означает начало, а ток - ток. (Я просто скопировал формулу о том, как получить расстояние от двух широты и долготы в Интернете)Ошибка приложения при достижении расстояния от двух широт и долготы

public Double getDistance(Double startLat, Double startLong, Double currLat, Double currLong) { 

    int radius = 6371; //This is the radius of the earth 
    Double distanceLatitude = degreeToRadius(currLat-startLat); 
    Double distanceLongitude = degreeToRadius(currLong-startLong); 
    Double area = 
      Math.sin(distanceLatitude/2) * Math.sin(distanceLatitude/2) + 
        Math.cos(degreeToRadius(startLat)) * Math.cos(degreeToRadius(currLat)) * 
          Math.sin(distanceLongitude/2) * Math.sin(distanceLongitude/2) 
      ; 
    Double circumference = 2 * Math.atan2(Math.sqrt(area), Math.sqrt(1-area)); 
    Double totalDistance = radius * circumference; 
    return totalDistance; 

} 

public Double degreeToRadius(Double degreeToRadius) { 
    return degreeToRadius * (Math.PI/180); 
} 

И это моя onLocationChanged функция, где он обновляет широту и долготу, когда устройство было перемещено и я также устанавливая расстояние здесь.

@Override 
public void onLocationChanged(Location location) { 

    String locationMessage = "Latitude: " + location.getLatitude() 
      + "Longitude: " + location.getLongitude(); 

    Double locationLatitude = location.getLatitude(); 
    Double locationLongitude = location.getLongitude(); 

    Toast.makeText(getBaseContext(), locationMessage, Toast.LENGTH_LONG).show(); 
    currentLatitude.setText(locationLatitude.toString()); 
    currentLongitude.setText(locationLongitude.toString()); 

    Double startLat = Double.parseDouble(startingLatitude.getText().toString()); 
    Double startLong = Double.parseDouble(startingLongitude.getText().toString()); 
    Double currLat = Double.parseDouble(currentLatitude.getText().toString()); 
    Double currLong = Double.parseDouble(currentLongitude.getText().toString()); 

    distance.setText(getDistance(startLat, startLong, currLat, currLong).toString() + "KM"); 

} 

Когда я запускаю приложение, оно работает нормально, но когда оно начинает получать местоположение, оно всегда сбой. Есть идеи? Пожалуйста помоги. Благодаря

Это журнал

E/AndroidRuntime: FATAL EXCEPTION: main 
       Process: com.example.webglider.fitnessapp, PID: 7600 
       java.lang.NumberFormatException: Invalid double: "" 
        at java.lang.StringToReal.invalidReal(StringToReal.java:63) 
        at java.lang.StringToReal.parseDouble(StringToReal.java:267) 
        at java.lang.Double.parseDouble(Double.java:301) 
        at com.example.webglider.fitnessapp.MainActivity.onLocationChanged(MainActivity.java:196) 
        at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:290) 
        at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:219) 
        at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:235) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:148) 
        at android.app.ActivityThread.main(ActivityThread.java:7325) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120) 

Это линия 196 на моем MainActivity.java

Double startLat = Double.parseDouble(startingLatitude.getText().toString()); 
+0

попробуйте это http://stackoverflow.com/questions/22577075/calculating-the-distance-between-two-latitude-and-longitude-points-in-android –

+0

аварийные журналы помогут вам отправить его на помощь. – Piyush

+0

Пожалуйста, разместите свой журнал –

ответ

0

Попробуйте код ниже. Местоположение класс в android имеет встроенный метод, чтобы получить расстояние между двумя точками. Это даст вам расстояние в метрах.

Location oldLocation = new Location("oldLocation");  
oldLocation.setLatitude(oldLat); 
oldLocation.setLongitude(oldLng); 
Location newLocation = new Location("newLocation"); 
newLocation.setLatitude(newLat); 
newLocation.setLongitude(newLng); 
float distance = oldLocation.distanceTo(newLocation) ; 

Для справки см. Официальную документацию. https://developer.android.com/reference/android/location/Location.html#distanceTo(android.location.Location)