如何使用Picasso加载Google地图静态地图?

时间:2013-12-10 16:16:53

标签: java android image google-maps picasso

在我的Android应用中,我使用Picasso来加载图片。这通常非常有效。

今天我尝试从google maps api加载静态图片,但这似乎不起作用。当我打开example link上提供的their info page时,我可以很好地看到静态地图图像。当我使用下面的行在我的Android应用程序中加载它时,我什么也得不到。

Picasso.with(getContext()).load("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false").into(mapView);

我还尝试下载图片并将其上传到我的个人网站空间loads perfectly well,但不知何故,它似​​乎无法直接从直接的Google API网址加载。

有人知道为什么会这样,以及我如何解决它?

3 个答案:

答案 0 :(得分:0)

想到的唯一程序化失败点是解析URI。查看当前的毕加索代码(https://github.com/square/picasso/blob/master/picasso/src/main/java/com/squareup/picasso/Picasso.java),我看到以下内容:

  public RequestCreator load(String path) {
    if (path == null) {
      return new RequestCreator(this, null, 0);
    }
     if (path.trim().length() == 0) {
      throw new IllegalArgumentException("Path must not be empty.");
    }
    return load(Uri.parse(path));
  }

所以我先调试

Uri.parse("http://maps.googleapis.com/maps/api/staticmap?center=Brooklyn+Bridge,New+York,NY&zoom=13&size=370x250&maptype=roadmap%20&markers=color:blue|label:S|40.702147,-74.015794&markers=color:green|label:G|40.711614,-74.012318%20&markers=color:red|color:red|label:C|40.718217,-73.998284&sensor=false")

并查看该Object的外观。它会丢失或混淆你的任何参数吗?

如果这不能引导您到达某处,请尝试使用HttpClient [或类似]手动下载文件。那么至少你可以完全调试请求/响应。

此外,我知道谷歌地图有一些限制 - 你确定你没有达到它们吗?

答案 1 :(得分:0)

  • http替换为https
  • 替换|与%7C
  • 添加api密钥

答案 2 :(得分:0)

.loadMap()函数具有许多声明的变量。这是整个过程的核心。

因此,静态地图API为我们提供图像所需的条件是,我们使用给定的URL发出http请求,并为此接收到图像响应(URL)。让我们来看一下这些变量的含义和效用。是的,它们的含义完全不同!

在进行API调用时,mapUrlInitial变量始终相同。它有一个中心查询(?center),它指定我们希望该位置在地图上居中。

mapUrlProperties变量包含一个字符串,您可以在其中控制将获得的图像响应的实际缩放,图像的大小和指示我们位置的标记的颜色。

mapUrlMapType变量是一个字符串,您可以在其中实际确定所需的标记大小和地图的类型。我们正在应用中使用路标地图。

最后latLong是一个字符串,将我们要确定的位置的纬度和经度连接起来!

然后,我们将所有这些字符串连接起来以形成可行的网址。然后,如上所见,在Picasso代码中加载了网址。我们可以注意到的一件事是,所有这些事情的发生总是需要一个事件对象,因为我们能够使用该事件对象来获取位置细节!最终代码:-

fun loadMap(event: Event): String{
  //location handling

  val mapUrlInitial = “https://maps.googleapis.com/maps/api/staticmap?center=”

  val mapUrlProperties = “&zoom=12&size=1200×390&markers=color:red%7C”

  val mapUrlMapType = “&markers=size:mid&maptype=roadmap”
  val latLong: String = “” +event.latitude + “,” + event.longitude
  return mapUrlInitial + latLong + mapUrlProperties + latLong + mapUrlMapType

}
//load image

Picasso.get()

      .load(loadMap(event))

      .placeholder(R.drawable.ic_map_black_24dp)

      .into(rootView.image_map)
相关问题