Tính Khoảng Cách Giữa 2 Địa Điểm Bằng Google Maps Api

  -  

Rất nhiều điều độc đáo có thể được tiến hành bằng phương pháp sử dụng API Google Maps. Ngày nay, các công ty trở nên tân tiến đang thể nghiệm cùng thực hiện những loại tài năng khác nhau, bao hàm cả tính năng tính tân oán khoảng cách giữa hai điểm hoặc tọa độ GPS vào Android ứng dụng di động. Điều này rất có thể giành được thông qua API Google Maps. Và nó đã tạo nên laptop khoảng cách tọa độ GPS dễ dàng tìm thấy hai bộ chuyển đổi tọa độ GPS bên trên bạn dạng thiết bị là bao xa.

Bạn đang xem: Tính khoảng cách giữa 2 địa điểm bằng google maps api

Nếu bạn đang xuất hiện planer trở nên tân tiến một vận dụng du ngoạn, theo dõi vị trí, đặt xe cộ taxi hoặc ngẫu nhiên vận dụng đặt xe cộ như thế nào, thì một thiên tài điều đó vô cùng bổ ích. Đã cải cách và phát triển rộng 50 áp dụng đặt xe taxi và hơn 40 vận dụng phục vụ theo thử dùng, Cửa Hàng chúng tôi đang thực hiện thiên tài này nhằm theo dõi thời hạn thực nhiều lần.

Trong bài viết về áp dụng Android này, Cửa Hàng chúng tôi phát triển một áp dụng kiểm tra hiển thị tuyến phố thân nhị địa điểm.

Tính khoảng cách giữa nhì điểm

Đây là quá trình từng bước một nhằm tính toán khoảng cách thân nhị điểm bằng cách thực hiện API Google Maps.

Tạo một dự án công trình bắt đầu trong menu phim trong Android Studio.


*

*


*

Bắt đầu tích đúng theo mã

Hoạt động chủ yêu

public class MainActivity extends AppCompatActivity implements ConstantInterface, OnMapReadyCallbaông chồng, DirectionCallbaông chồng,GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListenerprivate SupportMapFragment mapFragment;private GoogleMap googleMap;private TextView textAddress;private LatLng currentLatLng;private GoogleApiClient googleApiClient;private LocationRequest locationRequest;private AppUtility appUtility;private RunTimePermission runTimePermission;
Overrideprotected void onCreate(Bundle savedInstanceState) super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);initControls();
Overridepublic void onStop() if (googleApiClient != null &và googleApiClient.isConnected()) googleApiClient.disconnect();super.onStop(); private void initControls() appUtility = new AppUtility(this);runTimePermission = new RunTimePermission(this);mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);textAddress = (TextView) findViewById(R.id.textAddress);textAddress.setOnClickListener(new View.OnClickListener()
Overridepublic void onClick(View view) // This is khổng lồ prevent user lớn cliông chồng on the maps under the distance text.);if (appUtility.checkPlayServices()) googleApiClient = new GoogleApiClient.Builder(this).addApi(LocationServices.API).addConnectionCallbacks(this).addOnConnectionFailedListener(this).build();googleApiClient.connect();
Overridepublic void onMapReady(final GoogleMap googleMap) this.googleMap = googleMap;if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) googleMap.setMyLocationEnabled(true);googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentLatLng));googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentLatLng, 15f));googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener()
Overridepublic void onMapClick(LatLng latLng) googleMap.clear();googleMap.addMarker(new MarkerOptions().position(latLng));GoogleDirection.withServerKey(getString(R.string.map_direction_key)).from(currentLatLng).to(new LatLng(latLng.latitude, latLng.longitude)).transportMode(TransportMode.DRIVING).execute(MainActivity.this);showDistance(latLng);); 
Overridepublic void onDirectionSuccess(Direction direction, String rawBody) if (direction.isOK()) ArrayList directionPositionList = direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();googleMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 1, ContextCompat.getColor(this, R.color.colorPrimary)));
Overridepublic void onDirectionFailure(Throwable t) private void showDistance(LatLng latLng) Location locationA = new Location("Location A");locationA.setLatitude(latLng.latitude);locationA.setLongitude(latLng.longitude);Location locationB = new Location("Location B");locationB.setLatitude(currentLatLng.latitude);locationB.setLongitude(currentLatLng.longitude);textAddress.setText("Distance : " + new DecimalFormat("##.##").format(locationA.distanceTo(locationB)) + "m");// checking Runtime permissionprivate void getPermissions(String<> strings) runTimePermission.requestPermission(strings, new RunTimePermission.RunTimePermissionListener()
Overridepublic void permissionGranted() locationChecker(googleApiClient, MainActivity.this);
Overridepublic void permissionDenied() setResult(RESULT_CANCELED);finish();); // Checking whether location service is enable or not.

Xem thêm: Cách Nhận Biết Bệnh Trầm Cảm, Biểu Hiện Bệnh Trầm Cảm Mức Độ Nhẹ

public void locationChecker(GoogleApiClient mGoogleApiClient, final Activity activity) // Creating location request objectlocationRequest = LocationRequest.create();locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);locationRequest.setInterval(UPDATE_INTERVAL);locationRequest.setSmallestDisplacement(DISPLACEMENT);LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);builder.setAlwaysShow(true);PendingResult result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());result.setResultCallback(new ResultCallback()
Overridepublic void onResult(LocationSettingsResult result) final Status status = result.getStatus();final LocationSettingsStates state = result.getLocationSettingsStates();switch (status.getStatusCode()) case LocationSettingsStatusCodes.SUCCESS:getLocation();break;case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:try status.startResolutionForResult(activity, 1000); catch (IntentSender.SendIntentException e) break;case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:break;);private void getLocation() if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, this);
Overridepublic void onConnected(
Nullable Bundle bundle) getPermissions(new String<>Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION);
Overridepublic void onConnectionSuspended(int i)
Overridepublic void onConnectionFailed(
NonNull ConnectionResult connectionResult)
Overridepublic void onLocationChanged(Location location) currentLatLng = new LatLng(location.getLatitude(), location.getLongitude());if (googleMap == null) mapFragment.getMapAsync(this);activitymain.xml

xml version="1.0" encoding="utf-8"?>AppUtility.java


public class AppUtility implements ConstantInterface private Context context;public AppUtility(Context context) this.context = context;// Cheông chồng weather google play services is available or not.public boolean checkPlayServices() GoogleApiAvailability googleAPI = GoogleApiAvailability.getInstance();int result = googleAPI.isGooglePlayServicesAvailable(context);if (result != ConnectionResult.SUCCESS) if (googleAPI.isUserResolvableError(result)) googleAPI.getErrorDialog((Activity) context, result, PLAY_SERVICES_RESOLUTION_REQUEST).show();return false;return true;RunTimePermission.java

public class RunTimePermission extends AppCompatActivity {private Activity activity;private ArrayList arrayListPermission;private String<> arrayPermissions;private RunTimePermissionListener runTimePermissionListener;public RunTimePermission(Activity activity) this.activity = activity;public class PermissionBean String permission;boolean isAccept;public void requestPermission(String<> permissions, RunTimePermissionListener runTimePermissionListener) {this.runTimePermissionListener = runTimePermissionListener;arrayListPermission = new ArrayList();if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) for (int i = 0; i = Build.VERSION_CODES.LOLLIPOP) adb = new AlertDialog.Builder(activity, android.R.style.Theme_Material_Light_Dialog_Alert); else adb = new AlertDialog.Builder(activity);adb.setTitle(activity.getResources().getString(R.string.app_name));String msg = "Dear User,

" +"

Seems like you have "Denied" the minimum requirement permission to access more features of application.

" +"

You must have sầu lớn "Allow" all permission. We will not giới thiệu your data with anyone else.

" +"

Do you want to enable all requirement permission ?

" +"

Go To : Settings >> App > " + activity.getResources().getString(R.string.app_name) + " Permission : Allow ALL


";adb.setMessage(Html.fromHtml(msg));adb.setPositiveButton("Allow All", new AlertDialog.OnClickListener()
Overridepublic void onClick(DialogInterface dialog, int which) callSettingActivity();dialog.dismiss(););adb.setNegativeButton("Remind Me Later", new AlertDialog.OnClickListener()
Overridepublic void onClick(DialogInterface dialog, int which) dialog.dismiss(););if (!((Activity) activity).isFinishing() &và msg.length() > 0) adb.show(); else Log.v("log_tag", "either activity finish or message length is 0");private void updatePermissionResult(String permissions, int grantResults) {for (int i = 0; i

ConstantInterface.java

public interface ConstantInterface int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;int UPDATE_INTERVAL = 10000; // 10 secint DISPLACEMENT = 10; // 10 metersStrings.xml

MapDirectionDemoYour hệ thống KeyDimensions.xml

22sp8dpAndroidManiFest.xml

 Và thực hiện!

Cuối thuộc, họ sẽ coi câu trả lời mang lại một vài thắc mắc phổ cập tốt nhất.


Các thắc mắc hay gặp

Quý Khách có thể làm những gì cùng với Google Map API?

quý khách rất có thể tạo ra bạn dạng đồ thiết lập cấu hình, lập planer tuyến phố, tra cứu khoảng cách giữa nhị hoặc nhiều điểm, chế tác bản đồ có thể tra cứu kiếm, quan sát và theo dõi thời gian thực, tác dụng đăng ký, đo quãng con đường theo con đường trực tiếp giữa hai thành thị, chỉ là 1 vài ba trong các những Việc bạn có thể làm.

Tôi rất có thể áp dụng Google Maps trong vận dụng của chính bản thân mình không?

Có, bạn có thể áp dụng những sản phẩm của Google Maps Platform trong cả bên trên các áp dụng chưa hẳn website. Điều khiếu nại duy nhất là chúng ta vâng lệnh những quy định thực hiện của Nền tảng Google Maps. Ngay cả Lúc áp dụng của bạn là ứng dụng truy vấn riêng biệt tứ, chúng ta vẫn hoàn toàn có thể áp dụng các các dịch vụ Google Maps, Tuyến đường với Địa điểm.

Quý khách hàng đã trở nên tân tiến ứng dụng làm sao gồm kỹ năng quan sát và theo dõi khoảng cách chưa?

Có, công ty chúng tôi đang cách tân và phát triển các vận dụng khác biệt sử dụng định vị GPS, theo dõi khoảng cách thời gian thực với các anh tài không giống. Trên thực tế, chúng tôi đã cải cách và phát triển hơn 50 ứng dụng tương tự Uber và hơn 40 áp dụng theo những hiểu biết. Một số trong các chính là Glovo, Bevy, Baloora với One-8.


Phần kết luận

Đây là giải pháp đơn giản dễ dàng và dễ ợt tốt nhất để tính khoảng cách giữa hai vĩ độ với vĩ độ vào vận dụng Android. API tọa độ của Google Maps cung cấp đến nhà cải cách và phát triển những chức năng để cung cấp cho những người sử dụng áp dụng.

Sau lúc hiểu nội dung bài viết này, bạn cũng có thể ý muốn biết về phong thái áp dụng Google Map Marker giúp thấy những dữ liệu bằng cách thực hiện cơ chế xem Android hoặc biện pháp vẽ một chốt vị trí bây chừ trên Google Map cùng với tính năng tra cứu kiếm thúc đẩy. Vì vậy, nếu như khách hàng bao gồm một ý tưởng ứng dụng liên quan mang lại nhu yếu về Google Maps vào vận dụng của mình, ví dụ như tính khoảng cách thân nhì điểm, thì bạn nên thực thi công dụng tính khoảng cách giữa hai tọa độ GPS.

Xem thêm: Hướng Dẫn Những Cách Lấy Cắp Mật Khẩu Gmail Của Người Khác, Cách Để Hack Gmail

Để tiến hành, chúng ta cũng có thể làm theo lí giải API Google Maps của Cửa Hàng chúng tôi hoặc mướn một công ty cách tân và phát triển áp dụng Android nếu như khách hàng bắt buộc cung ứng chuyên môn để thêm vận dụng cội của bản thân. Nhận bản sao mã miễn mức giá để tính tân oán khoảng cách thân nhì bạn dạng biểu diễn điểm bằng Google Maps từ Github.