Android谷歌地圖使用地理編碼器搜索位置含代碼

Android谷歌地圖使用地理編碼器搜索位置

在之前的Android谷歌地圖和Android谷歌地圖顯示當前位置的教程中,我們分別介紹了顯示基本谷歌地圖和當前位置的功能。愛掏網 - it200.com

現在,在這個教程中我們將實現谷歌地圖的位置搜索功能。愛掏網 - it200.com

通過谷歌地圖API搜索位置是通過 Geocoder 類來完成的。愛掏網 - it200.com Geocoder類用于處理 地理編碼 和 逆地理編碼 。愛掏網 - it200.com

地理編碼是將街道地址轉換為坐標(緯度,經度)的過程。愛掏網 - it200.com逆地理編碼是將坐標(緯度,經度)轉換為地址的過程。愛掏網 - it200.com

  1. **List <Address> getFromLocation(double latitude, double longitude, int maxResults): ** 此方法返回一個指定周圍緯度和經度的Address數組。愛掏網 - it200.com
  2. **List <Address> getFromLocationName(String location, int results, double leftLatitude, double leftLongitude, double rightLatitude, double rightLongitude): ** 此方法返回一個描述給定位置(如地點、地址等)的Address數組。愛掏網 - it200.com
  3. **List <Address> getFromLocationName(String location, int results): ** 此方法返回一個描述給定位置(如地點、地址等)的Address數組。愛掏網 - it200.com
  4. static boolean isPresent(): 此方法如果實現了getFromLocation()和 getFromLocationName()方法,則返回true。愛掏網 - it200.com

讓我們來看一下將位置名稱轉換為坐標的代碼。愛掏網 - it200.com

List<Address> addressList = geocoder.getFromLocationName(location, 1);
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());

例子:Android谷歌地圖API搜索位置

讓我們看一個搜索輸入位置的谷歌地圖的例子。愛掏網 - it200.com

activity_maps.xml

在activity_maps.xml文件中添加一個片段(SupportMapFragment)、一個EditText和一個按鈕。愛掏網 - it200.com

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.com.mapexample.MapsActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <EditText
            android:layout_width="248dp"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:layout_weight="0.5"
            android:inputType="textPersonName"
            android:hint="Search Location" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:onClick="searchLocation"
            android:text="Search" />

    </LinearLayout>

</fragment>

build.gradel

在 build.gradel 文件中添加以下依賴項。愛掏網 - it200.com

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.google.android.gms:play-services-maps:11.8.0'
    compile 'com.google.android.gms:play-services-location:11.8.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

}

MapsActivity.java

在MapsActivity.java文件中添加以下代碼。愛掏網 - it200.com

package example.com.mapexample;

import android.location.Address;
import android.location.Geocoder;
import android.os.Build;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.location.LocationServices;

import android.location.Location;
import android.Manifest;
import android.content.pm.PackageManager;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

import java.io.IOException;
import java.util.List;


public class MapsActivity extends FragmentActivity implements OnMapReadyCallback,
        LocationListener,GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener{

    private GoogleMap mMap;
    Location mLastLocation;
    Marker mCurrLocationMarker;
    GoogleApiClient mGoogleApiClient;
    LocationRequest mLocationRequest;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }

    }
    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API).build();
        mGoogleApiClient.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(mGoogleApiClient, mLocationRequest, this);
        }

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @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("Current Position");
        markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
        mCurrLocationMarker = mMap.addMarker(markerOptions);

        //move map camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //stop location updates
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    public void searchLocation(View view) {
        EditText locationSearch = (EditText) findViewById(R.id.editText);
        String location = locationSearch.getText().toString();
        List<Address> addressList = null;

        if (location != null || !location.equals("")) {
            Geocoder geocoder = new Geocoder(this);
            try {
                addressList = geocoder.getFromLocationName(location, 1);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Address address = addressList.get(0);
            LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
            mMap.addMarker(new MarkerOptions().position(latLng).title(location));
            mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            Toast.makeText(getApplicationContext(),address.getLatitude()+" "+address.getLongitude(),Toast.LENGTH_LONG).show();
        }
    }

}

在AndroidManifest.xml中需要添加的權限

在AndroidManifest.xml文件中添加以下用戶權限。愛掏網 - it200.com

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

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="example.com.mapexample">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

</manifest>

輸出

聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
發表評論
更多 網友評論0 條評論)
暫無評論

返回頂部

主站蜘蛛池模板: 韩国本免费一级毛片免费| www视频免费看| 日韩欧美在线播放| 全部免费a级毛片| 18女人腿打开无遮挡软| 无翼乌口工全彩无遮挡里| 人妻内射一区二区在线视频| 欧美激情性xxxxx| 嫩b人妻精品一区二区三区| 亚洲中文无码a∨在线观看| 老司机精品视频在线| 国产超碰人人爽人人做人人添| 久久大香伊人中文字幕| 男女男精品网站| 国产大片免费天天看| chinese国产xxxx实拍| 日韩欧美三级在线观看| 人妻少妇精品久久久久久| 黄在线观看网站| 在线观看黄日本高清视频| 久久精品*5在热| 波多野结衣和乡下公在线观看| 国产午夜福利短视频| 99久久精品美女高潮喷水| 日本视频免费看| 亚洲欧美日韩中文字幕一区二区三区| 草莓视频黄瓜视频| 国产精品美女久久久网av| 中文字幕在线网| 欧美a级v片在线观看一区| 再深点灬好舒服灬太大了添| 黑白禁区高清免费观看全集电视剧| 女律师的堕落高清hd| 久久机热这里只有精品无需| 波多野结衣在线看片| 国产91精品一区二区视色| 抽搐一进一出gif免费视频| 女女同性一区二区三区四区| 久久福利一区二区| 欧美日韩亚洲电影网在线观看| 又大又粗又爽的三级小视频|