android 静态_Google静态地图Android

android 静态

In this tutorial we’re going to implement a google static maps in our android application. Google Static Maps API typically shows fewer points of interest compared to Google Maps.

在本教程中,我们将在我们的android应用程序中实现google静态地图。 与Google Maps相比,Google Static Maps API通常显示较少的兴趣点。

Google静态地图
  1. Google Static Maps API允许我们根据通过标准HTTP请求发送的URL参数(即纬度,经度,缩放级别,编码折线等)动态创建地图图像。 调用时,它将地图作为图像返回,允许开发人员在用户界面上显示它。
  2. Google Static Maps API通过URL响应HTTP请求,返回图像(GIF,PNG或JPEG)。 对于每个请求,我们可以指定地图的位置,图像的大小,缩放级别,地图的类型以及可选标记在地图上位置的位置。 我们还可以使用一些标准的字母数字字符标记您的标记。
(Google Static Maps
  1. Google Static Maps API allow us to dynamically create a map image based on URL parameters (i.e. latitude, longitude, zoom level, encoded polyline etc.) sent through a standard HTTP request. When called, it returns the map as an image allowing developers to display it on the user interface.
  2. Google Static Maps API returns an image (either GIF, PNG or JPEG) in response to an HTTP request via a URL. For each request, we can specify the location of the map, the size of the image, the zoom level, the type of map, and the placement of optional markers at locations on the map. We can additionally label your markers using some standard alphanumeric characters.
)

A Google Static Map must be of the form:

Google静态地图必须采用以下形式:

https://maps.googleapis.com/maps/api/staticmap?parameters

The parameters of the url must be properly URL encoded before the http request is sent.

发送http请求之前,必须对URL的参数进行正确的URL编码。

Google静态地图参数 (Google Static Maps parameters)

Some required parameters for google static maps are described below.

Google静态地图的一些必需参数如下所述。

  1. center: This defines the center of the map, equidistant from all edges of the map. This parameter takes a location as either a comma-separated {latitude, longitude} pair (e.g. “40.714728,-73.998672”) or a string address (e.g. “city hall, new york, ny”) identifying a unique location on the face of the earth.

    center :定义地图中心,与地图所有边缘等距。 此参数以逗号分隔的{纬度,经度}对(例如“ 40.714728,-73.998672”)或字符串地址(例如“市政厅,纽约,纽约州”)作为标识唯一位置的位置作为位置地球。
  2. zoom: This defines the zoom level of the map, which determines the magnification level of the map. This parameter takes a numerical value corresponding to the zoom level of the region desired.

    zoom :定义地图的缩放级别,该级别确定地图的放大级别。 该参数采用与所需区域的缩放级别相对应的数值。
  3. size: This defines the rectangular dimensions of the map image. This parameter takes a string of the form {horizontal_value}x{vertical_value}. For example, 500×400 defines a map 500 pixels wide by 400 pixels high.

    size :这定义了地图图像的矩形尺寸。 此参数采用{horizo​​ntal_value} x {vertical_value}形式的字符串。 例如,500×400定义了一个500像素宽乘400像素高的地图。

Several other parameters like markers and path take multiple locations. In those cases, the locations are separated by the pipe (|) character.

markerspath等其他几个参数也位于多个位置。 在这些情况下,位置之间用竖线(|)分隔。

Google静态地图Android应用程序 (Google Static Maps Android Application)

Let’s create an application that returns a google static map image and display it in a circular ImageView.

让我们创建一个返回google静态地图图像并将其显示在圆形ImageView中的应用程序。

Below image shows the android studio project structure.

下图显示了android studio项目的结构。

Google静态地图Android代码 (Google Static Maps Android Code)

In this tutorial we’ve used a third party library to create a CircularImageView. We recommend using and integrating third party libraries wherever feasible as it saves time in writing some standard custom classes that are pretty common.

在本教程中,我们使用了第三方库来创建CircularImageView。 我们建议在可行的情况下使用和集成第三方库,因为这样可以节省编写一些常见的标准自定义类的时间。

compile 'com.pkmmte.view:circularimageview:1.1'

To send and receive the http url and response you need to add a few jar files in the project.

要发送和接收http url和响应,您需要在项目中添加一些jar文件。

  • httpclient-4.3.3.jar

    httpclient-4.3.3.jar
  • httpcore-4.3.3.jar

    httpcore-4.3.3.jar
  • httpmime-4.3.3.jar

    httpmime-4.3.3.jar

Sync the gradle dependencies to add the libraries in the project. On running this project now a DuplicateFileExpection might arise in the build.gradle. It’s due to conflicting package files of the libraries. A workaround is adding the following in the android tag of the build.gradle file.

同步gradle依赖项以将库添加到项目中。 现在,在运行该项目时, build.gradle中可能会出现DuplicateFileExpection 。 这是由于库的软件包文件冲突。 解决方法是在build.gradle文件的android标签中添加以下内容。

packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }

The content_main.xml is defined as below.

content_main.xml定义如下。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:background="@android:color/black"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.journaldev.staticmaps.MainActivity"
    tools:showIn="@layout/activity_main">

    <com.pkmmte.view.CircularImageView
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:clickable="true"
        android:id="@+id/img_map_route"
        android:layout_gravity="center"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />


</RelativeLayout>

The MainActivity.java looks like below.

MainActivity.java如下所示。

package com.journaldev.staticmaps;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import com.pkmmte.view.CircularImageView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity {

    private String STATIC_MAP_API_ENDPOINT = "https://maps.googleapis.com/maps/api/staticmap?size=230x200&path=";
    String path;


    CircularImageView iv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        iv=(CircularImageView)findViewById(R.id.img_map_route);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        try {

            String marker_me = "color:orange|label:1|Brisbane";
            String marker_dest = "color:orange|label:7|San Francisco,USA";
            marker_me = URLEncoder.encode(marker_me, "UTF-8");

            marker_dest = URLEncoder.encode(marker_dest, "UTF-8");
            path = "weight:3|color:blue|geodesic:true|Brisbane,Australia|Hong Kong|Moscow,Russia|London,UK|Reyjavik,Iceland|New York,USA|San Francisco,USA";
            path = URLEncoder.encode(path, "UTF-8");

            STATIC_MAP_API_ENDPOINT = STATIC_MAP_API_ENDPOINT + path + "&markers=" + marker_me + "&markers=" + marker_dest;

            Log.d("STATICMAPS", STATIC_MAP_API_ENDPOINT);

            AsyncTask<Void, Void, Bitmap> setImageFromUrl = new AsyncTask<Void, Void, Bitmap>(){
                @Override
                protected Bitmap doInBackground(Void... params) {
                    Bitmap bmp = null;
                    HttpClient httpclient = new DefaultHttpClient();
                    HttpGet request = new HttpGet(STATIC_MAP_API_ENDPOINT);

                    InputStream in = null;
                    try {
                        HttpResponse response = httpclient.execute(request);
                        in = response.getEntity().getContent();
                        bmp = BitmapFactory.decodeStream(in);
                        in.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return bmp;
                }
                protected void onPostExecute(Bitmap bmp) {
                    if (bmp!=null) {

                        iv.setImageBitmap(bmp);

                    }

                }
            };

            setImageFromUrl.execute();

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    @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 boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

In the above code we’ve url encoded the markers parameters and path parameters using URLEncoder.encode(path, "UTF-8");.

在上面的代码中,我们使用URLEncoder.encode(path, "UTF-8");对标记参数和路径参数进行了url编码URLEncoder.encode(path, "UTF-8");

This makes the string url compatible by removing the white spaces and replacing them by %20C etc.

这可以通过删除空格并将其替换为%20C等来使字符串url兼容。

An AsyncTask anonymous inner class is created that sends the encoded static map api url using http call and the response returned is the Bitmap static map image of the url.
That bitmap is loaded into the CircularImageView. The following snippet is used to decode the Bitmap from the response stream.

创建一个AsyncTask匿名内部类,该内部类使用http调用发送编码的静态地图api url,返回的响应是该URL的Bitmap静态地图图像。
该位图被加载到CircularImageView中。 以下代码段用于从响应流中解码位图。

bmp = BitmapFactory.decodeStream(in);

In this example we’ve set two markers and a path consisting of some prominent landmarks across the globe. For many points along the path we can pass an encoded polyline string too. This will be discussed in a later tutorial.

在此示例中,我们设置了两个标记和一条路径,该路径由全球一些著名的地标组成。 对于路径上的许多点,我们也可以传递编码的折线字符串。 这将在以后的教程中讨论。

The output of the application is given below:

android google static map

该应用程序的输出如下:

This brings an end to google static maps android application tutorial. You can download the final Android StaticMaps Project from the link below.

这结束了Google静态地图android应用程序教程。 您可以从下面的链接下载最终的Android StaticMaps项目。

Reference: Official Documentation

参考: 官方文档

翻译自: https://www.journaldev.com/10392/google-static-maps-android

android 静态

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值