1. ホーム
  2. Android Studio

Android Studioによる地図開発(Baidu Map)

2022-02-17 16:20:30
<パス

プロジェクトは数日中にgithubに送信されますので、参考にしてください
マッププロジェクト例 https://github.com/wangleihitcs/MyMap/tree/master

ステップ1. 環境を設定する

1. Baiduマップキーの適用

  • まず、以下のサイトにアクセスします。 Baidu Mapsオープンプラットフォーム をクリックし、アカウントにログインして、次の画面に進んでください。
  • アプリを作成する」をクリックし、以下の画面に進み、アプリ名を入力し、アプリの種類として「Android SDK」を選択します。
  • リリース版のSHA1と開発版のSHA1を取得する、リンクは次の通りです。 Baiduは、SHA1を取得する方法を提供しています。 なお、SHA1はfile.jksをベースに、開発版のSHA1はデバッグ時に使用しdebug.jksをベースに、リリース版はアプリやapkのリリース時に使用し、作成したxxx.jksをベースにします。あなたが唯一のキーを取得するためにSHA1のリリース版を記入した場合、デバッグ時間は、Baiduの地図が表示されていない、覚えている![OK]をクリックします。
2. Baidu Mapsの基本的なjarパッケージのインポートとsoファイル

  • jarパッケージはlibsディレクトリにインポートされ、ここでは以下のように最もシンプルなBaiduLBS_Android.jarだけがインポートされています。
  • mainフォルダの下にjniLibsディレクトリを作成し、以下のようにsoファイルをインポートします。ここで注意するのは、armとx86のディレクトリにあるsoファイルは同じものですが、異なるCPU(arm、x86)用に設定されていることです。armeabiしかない場合、x86仮想マシンではBaiduマップを表示することができません!

ステップ2、基本開発

基本的な機能は、位置情報、緯度・経度・住所を元にした問い合わせなど、簡単な操作です。

  • AndroidManifest.xmlファイルに許可証、Baiduキーなどを追加する。
Add menu_item.xml to the menu directory <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="com.example.zhangyi.baidumap_test.MainActivity"> <item android:id="@+id/menu_item_mylocation" android:title="My Location" app:showAsAction="never" /> <item android:id="@+id/menu_item_llsearch" android:title="latitude&longitude search" app:showAsAction="never" /> <item android:id="@+id/menu_item_sitesearch" android:title="Address Search" app:showAsAction="never" /> </menu> In MainActivity.java package com.example.wanglei.mymap; import android.content.Context; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.Toast; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.SDKInitializer; import com.baidu.mapapi.map; import com.baidu.mapapi.map.BitmapDescriptor; import com.baidu.mapapi.ma private LinearLayout myLinearLayout2; //address search area 2 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // requestWindowFeature(Window.FEATURE_NO_TITLE); SDKInitializer.initialize(getApplicationContext()); setContentView(R.layout.activity_main); this.context = this; initView(); initLocation(); } private void initView() { myMapView = (MapView) findViewById(R.id.baiduMapView); myBaiduMap = myMapView.getMap(); //scale map level according to the given increment MapStatusUpdate msu= MapStatusUpdateFactory.zoomTo(18.0f); myBaiduMap.setMapStatus(msu); } private void initLocation() { locationMode = MyLocationConfiguration.LocationMode.NORMAL; // Client of the location service. The host program declares such on the client side and calls it, currently only supports starting in the main thread mylocationClient = new LocationClient(this); mylistener = new MylocationListener(); //register the listener mylocationClient.registerLocationListener(mylistener); //configure the location SDK configuration parameters, such as location mode, location time interval, coordinate system type, etc. LocationClientOption mOption = new LocationClientOption(); //set the coordinate type mOption.setCoorType("bd09ll"); //set whether address information is required, default is no address mOption.setIsNeedAddress(true); //set whether to open gps for location mOption.setOpenGps(true); //set the scan interval in milliseconds When <1000(1s), the timed positioning is invalid int span = 1000; mOption.setScanSpan(span); //set LocationClientOption mylocationClient.setLocOption(mOption); //initialize the icon, BitmapDescriptorFactory is the bitmap description information factory class. myIconLocation1 = BitmapDescriptorFactory.fromResource(R.drawable.location_marker); // myIconLocation2 = BitmapDescriptorFactory.fromResource(R.drawable.icon_target); // configuration of the location layer display, three parameter constructor MyLocationConfiguration configuration = new MyLocationConfiguration(locationMode, true, myIconLocation1); // Set the location layer configuration information, only after allowing the location layer first will the location layer configuration information take effect, see setMyLocationEnabled(boolean) myBaiduMap.setMyLocationConfigeration(configuration); myOrientationListener = new MyOrientationListener(context); //real-time orientation change via interface callback myOrientationListener.setOnOrientationListener(new MyOrientationListener.OnOrientationListener() { @Override public void onOrientationChanged(float x) { myCurrentX = x; } }); } /* * Create a menu operation */ @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { /* * The first function that returns the position where you are, indicated by the arrow */ case R.id.menu_item_mylocation:// return the current location getLocationByLL(myLatitude, myLongitude); break; /* * Second function, go to the location based on longitude and latitude */ case R.id.menu_item_llsearch:// Search for locations based on latitude and longitude myLinearLayout1 = (LinearLayout) findViewById(R.id.linearLayout1); //Longitude and latitude input area 1 is visible myLinearLayout1.setVisibility(View.VISIBLE); final EditText myEditText_lg = (EditText) findViewById(R.id.editText_lg); final EditText myEditText_la = (EditText) findViewById(R.id.editText_la); Button button_ll = (Button) findViewById(R.id.button_llsearch); button_ll.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View MainActivity.java same directory, AddressToLatitudeLongitude.java package com.example.wanglei.mymap; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; URLConnection; /** * Created by wanglei on 2017/6/20. * Get the latitude and longitude from the address according to Baidu map API */ public class AddressToLatitudeLongitude { private String address = "Harbin";//address private double Latitude = 45.7732246332393;//latitude private double Longitude = 126.65771685544611;//longitude public AddressToLatitudeLongitude(String addr_str) { this.address = addr_str; } /* * Get the geographic coordinates based on the address */ public void getLatAndLngByAddress(){ String addr = ""; String lat = ""; String lng = ""; try { addr = java.net.URLEncoder.encode(address,"UTF-8");//encoding } catch (UnsupportedEncodingException e) { e.printStackTrace(); } String url = String.format("http://api.map.baidu.com/geocoder/v2/? " +"address=%s&ak=4rcKAZKG9OIl0wDkICSLx8BA&output=json",addr); URL myURL = null; URLConnection httpsConn = null; //transcode try { myURL = new URL(url); } catch (MalformedURLException e) { e.printStackTrace(); } try { httpsConn = (URLConnection) myURL.openConnection();//establish connection if (httpsConn ! = null) { InputStreamReader insr = new InputStreamReader(//transfer data) httpsConn.getInputStream(), "UTF-8"); BufferedReader br = new BufferedReader(insr); String data = null; if ((data = br.readLine()) ! = null) { System.out.println(data); //here the data is the following json format string, because simple, so do not use json parsing, direct string processing //{"status":0,"result":{"location":{"lng":118.77807440802562,"lat": 32.05723550180587},"precise":0,"confidence":12,"level":"urban"}} lat = data.substring(data.indexOf("\"lat\":")+("\"lat\":").length(), data.indexOf("},\& quot;precise\"" ")); lng = data.substring(data.indexOf("\"lng\":")+("\"lng\":").length(), data.indexOf("\",\& quot;lat\"")); } insr.close(); br.close(); } } catch (IOException e) { e.printStackTrace(); } this.Latitude = Double.parseDouble(lat); this.Longitude = Double.parseDouble(lng); } public Double getLatitude() { return this.Latitude; } public Double getLongitude() { return this.Longitude; } public static void main(String[] args) { AddressToLatitudeLongitude at = new AddressToLatitudeLongitude("Bozhou City, Anhui Province, Bozhou a middle school "); at.getLatAndLngByAddress(); System.out.println(at.getLatitude() + " " + at.getLongitude()); } } As above, MyOrientationListener.java package com.example.wanglei.mymap; import android.content; import android.hardware.Sensor; import android.hardware.SensorEvent; SensorEvent; import android.hardware; SensorManager; import android.hardware; public class MyOrientationListener implements SensorEventListener{ private SensorManager mSensorManager; private Sensor mSensor; private Context mContext; private float lastX; private OnOrientationListener mOnOrientationListener; public MyOrientationListener(Context context) { this.mContext=context; } public void start() { mSensorManager= (SensorManager) mContext .getSystemService(Context.SENSOR_SERVICE); if(mSensorManager!= null) { //Get the direction sensor mSensor=mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION); } // determine if there is a direction sensor if(mSensor!=null) { //register the listener mSensorManager.registerListener(this,mSensor,SensorManager.SENSOR_DELAY_UI); } } public void stop() { mSensorManager.unregisterListener(this); } //change direction @Override public void onSensorChanged(SensorEvent event) { if(event.sensor.getType()==Sensor.TYPE_ORIENTATION) { float x=event.values[SensorManager.DATA_X]; if(Math.abs(x-lastX)>1.0) { if(mOnOrientationListener!=null) { mOnOrientationListener.onOrientationChanged(x); } } lastX=x; } } public void setOnOrientationListener(OnOrientationListener listener) { mOnOrientationListener=listener; } public interface OnOrientationListener { void onOrientationChanged(float x); } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } } Screenshot of document organization
Screenshot of the app running



Refer to the following link Return latitude and longitude based on Baidu API address
The most detailed BaiduMap development tutorial for Android Studio, which can be used as the official documentation tutorial!