- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在开发一个 Android 应用程序,我可以在其中获取用户的当前位置并显示该位置周围的某些地方。对于我的应用程序,我正在寻找的地方是医院,因此搜索 URL 是:
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types=hospital|health"+
"My_API_KEY_HERE";
我面临的问题是显示地点,我在手机上运行该应用程序,它可以运行并显示我的位置,但没有别的(我为每个位置使用不同的标记)。
我尝试使用文本搜索请求,但得到了相同的结果。
这是 MainActivity 类:
package com.location.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
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 android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
public class MyMapActivity extends Activity implements LocationListener {
//instance variables for Marker icon drawable resources
private int userIcon, foodIcon, drinkIcon, shopIcon, otherIcon;
//the map
private GoogleMap theMap;
//location manager
private LocationManager locMan;
//user marker
private Marker userMarker;
//places of interest
private Marker[] placeMarkers;
//max
private final int MAX_PLACES = 20;//most returned from google
//marker options
private MarkerOptions[] places;
@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((MapFragment)getFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
//update location
updatePlaces();
}
}
}
//location listener functions
@Override
public void onLocationChanged(Location location) {
Log.v("MyMapActivity", "location changed");
updatePlaces();
}
@Override
public void onProviderDisabled(String provider){
Log.v("MyMapActivity", "provider disabled");
}
@Override
public void onProviderEnabled(String provider) {
Log.v("MyMapActivity", "provider enabled");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v("MyMapActivity", "status changed");
}
/*
* update the place markers
*/
private void updatePlaces(){
//get location manager
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.icon(BitmapDescriptorFactory.fromResource(userIcon))
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types=hospital|health"+
"API_KEY";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
private class GetPlaces extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... placesURL) {
//fetch places
//build result as string
StringBuilder placesBuilder = new StringBuilder();
//process search parameter string(s)
for (String placeSearchURL : placesURL) {
HttpClient placesClient = new DefaultHttpClient();
try {
//try to fetch the data
//HTTP Get receives URL string
HttpGet placesGet = new HttpGet(placeSearchURL);
//execute GET with Client - return response
HttpResponse placesResponse = placesClient.execute(placesGet);
//check response status
StatusLine placeSearchStatus = placesResponse.getStatusLine();
//only carry on if response is OK
if (placeSearchStatus.getStatusCode() == 200) {
//get response entity
HttpEntity placesEntity = placesResponse.getEntity();
//get input stream setup
InputStream placesContent = placesEntity.getContent();
//create reader
InputStreamReader placesInput = new InputStreamReader(placesContent);
//use buffered reader to process
BufferedReader placesReader = new BufferedReader(placesInput);
//read a line at a time, append to string builder
String lineIn;
while ((lineIn = placesReader.readLine()) != null) {
placesBuilder.append(lineIn);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
return placesBuilder.toString();
}
//process data retrieved from doInBackground
protected void onPostExecute(String result) {
//parse place data returned from Google Places
//remove existing markers
if(placeMarkers!=null){
for(int pm=0; pm<placeMarkers.length; pm++){
if(placeMarkers[pm]!=null)
placeMarkers[pm].remove();
}
}
try {
//parse JSON
//create JSONObject, pass stinrg returned from doInBackground
JSONObject resultObject = new JSONObject(result);
//get "results" array
JSONArray placesArray = resultObject.getJSONArray("results");
//marker options for each place returned
places = new MarkerOptions[placesArray.length()];
//loop through places
for (int p=0; p<placesArray.length(); p++) {
//parse each place
//if any values are missing we won't show the marker
boolean missingValue=false;
LatLng placeLL=null;
String placeName="";
String vicinity="";
int currIcon = otherIcon;
try{
//attempt to retrieve place data values
missingValue=false;
//get place at this index
JSONObject placeObject = placesArray.getJSONObject(p);
//get location section
JSONObject loc = placeObject.getJSONObject("geometry")
.getJSONObject("location");
//read lat lng
placeLL = new LatLng(Double.valueOf(loc.getString("lat")),
Double.valueOf(loc.getString("lng")));
//get types
JSONArray types = placeObject.getJSONArray("types");
//loop through types
for(int t=0; t<types.length(); t++){
//what type is it
String thisType=types.get(t).toString();
//check for particular types - set icons
if(thisType.contains("hospital")){
currIcon = foodIcon;
break;
}
else if(thisType.contains("health")){
currIcon = drinkIcon;
break;
}
else if(thisType.contains("doctor")){
currIcon = shopIcon;
break;
}
}
//vicinity
vicinity = placeObject.getString("vicinity");
//name
placeName = placeObject.getString("name");
}
catch(JSONException jse){
Log.v("PLACES", "missing value");
missingValue=true;
jse.printStackTrace();
}
//if values missing we don't display
if(missingValue) places[p]=null;
else
places[p]=new MarkerOptions()
.position(placeLL)
.title(placeName)
.icon(BitmapDescriptorFactory.fromResource(currIcon))
.snippet(vicinity);
}
}
catch (Exception e) {
e.printStackTrace();
}
if(places!=null && placeMarkers!=null){
for(int p=0; p<places.length && p<placeMarkers.length; p++){
//will be null if a value was missing
if(places[p]!=null)
placeMarkers[p]=theMap.addMarker(places[p]);
}
}
}
}
@Override
protected void onResume() {
super.onResume();
if(theMap!=null){
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
}
@Override
protected void onPause() {
super.onPause();
if(theMap!=null){
locMan.removeUpdates(this);
}
}
}
布局:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/the_map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
map:cameraTilt="45"
map:cameraZoom="14"
/>
和 Manifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.location.test"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="22" />
<permission
android:name="com.location.test.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-permission android:name="com.location.test.permission.MAPS_RECEIVE"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyMapActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.gms.version"
android:value="@integer/google_play_services_version" />
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY" />
</application>
</manifest>
至于标记,它们只是 drawble 文件夹中的 4 个标记。任何人都知道如何解决这个问题?
最佳答案
我认为可以使用 Google Places API Web 服务而不是 Android SDK,因为 PlaceFilter来自 Android SDK 的只能通过 openNow
和 placeID
进行过滤。 Web Service的优点是它还可以通过radius
、minPrice
和maxPrice
等方式过滤结果
您的代码中存在多个问题。
首先你的请求URL中没有&key=
,所以应该是
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types=hospital|health"+
"&key=YOUR_API_KEY";
其次,您应该使用 HTTPURLConnection
类而不是旧的 HttpGet
类,因此您应该修改您的 doInBackground
方法,如下所示:
@Override
protected String doInBackground(String... placesURL) {
//fetch places
StringBuilder placesBuilder = new StringBuilder();
for (String placeSearchURL : placesURL) {
try {
URL requestUrl = new URL(placeSearchURL);
HttpURLConnection connection = (HttpURLConnection)requestUrl.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader reader = null;
InputStream inputStream = connection.getInputStream();
if (inputStream == null) {
return "";
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
placesBuilder.append(line + "\n");
}
if (placesBuilder.length() == 0) {
return "";
}
Log.d("test", placesBuilder.toString());
}
else {
Log.i("test", "Unsuccessful HTTP Response Code: " + responseCode);
}
} catch (MalformedURLException e) {
Log.e("test", "Error processing Places API URL", e);
} catch (IOException e) {
Log.e("test", "Error connecting to Places API", e);
}
}
return placesBuilder.toString();
}
第三,您将 locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
放在您的 updatePlaces()
方法中,您应该将其删除,因为它会不断循环 updatePlaces()
方法,这对您的应用程序和 API 配额限制不利。还要删除 onCreate()
方法中的 updatePlaces()
方法,并将这两行改为:
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
所以你更新的 onCreate()
和 updatePlaces()
应该是这样的:
onCreate():
@SuppressLint("NewApi") @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);
//get drawable IDs
userIcon = R.drawable.yellow_point;
foodIcon = R.drawable.red_point;
drinkIcon = R.drawable.blue_point;
shopIcon = R.drawable.green_point;
otherIcon = R.drawable.purple_point;
//find out if we already have it
if(theMap==null){
//get the map
theMap = ((SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.the_map)).getMap();
//check in case map/ Google Play services not available
if(theMap!=null){
//ok - proceed
theMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//create marker array
placeMarkers = new Marker[MAX_PLACES];
//update location
locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locMan.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, this);
}
}
}
更新地点():
private void updatePlaces(){
//get location manager
//get last location
Location lastLoc = locMan.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double lat = lastLoc.getLatitude();
double lng = lastLoc.getLongitude();
//create LatLng
LatLng lastLatLng = new LatLng(lat, lng);
//remove any existing marker
if(userMarker!=null) userMarker.remove();
//create and set marker properties
userMarker = theMap.addMarker(new MarkerOptions()
.position(lastLatLng)
.title("You are here")
.snippet("Your last recorded location"));
//move to location
theMap.animateCamera(CameraUpdateFactory.newLatLng(lastLatLng), 3000, null);
//build places query string
String placesSearchStr = "https://maps.googleapis.com/maps/api/place/nearbysearch/" +
"json?location="+lat+","+lng+
"&radius=1000&sensor=true" +
"&types=hospital|health"+
"&key=YOUR_API_KEY";//ADD KEY
//execute query
new GetPlaces().execute(placesSearchStr);
}
您还可以看到 updated code snippet . (我在这里扩展了 FragmentActivity
,因为我使用了 SupportMapFragment
)
您还可以在此处查看带标记的图像。 (我没有你的标记图片,所以我在这里使用默认的标记图片)
关于android - 如何使用 Google Places API 在 android 中显示附近搜索的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30336876/
我的子查询给出了一个错误:Msg 102, Level 15, State 1, Line 17 Incorrect syntax near ')'. SELECT SalesArea, Branch
当我尝试运行此查询时: select branch_no, max (avg_salary) from (select allocatedto, avg (salary) from sta
所以我正在更新 phpmyadmin 中的表。数据在里面,列已成功创建。当我尝试使用下面的代码添加图像时,出现此错误 Unexpected character. (near "\" at positi
我正在尝试在 phpMyAdmin 中执行以下查询,但出现错误。我已经查看过类似的问题,但我仍然无法弄清楚为什么它不起作用。 INSERT INTO discussion_forum (event_t
我正在用 C 构建一个 client-server socket 模拟 我接受来自客户端的 TCP 连接 然后客户端发送消息到我的服务器。我已成功收到消息,然后遍历 structs 的 array 以
我在 AUTOINCREMENT 附近遇到语法错误。这个错误的原因是什么? CREATE TABLE person ( id INTEGER NOT NULL AUTOINCREMENT,
当我尝试使用 java 在 SQLite 中以编程方式创建数据库时,它会在控制台中生成以下错误。 java.sql.SQLException: near "DATABASE": syntax erro
我似乎无法弄清楚出了什么问题。我尝试查询的子部分,但仍然无法解决问题。 表格格式: poi(id int, minX float, minY float, maxX float, maxY float
我在VHDL中编写了以下代码: library IEEE ; use IEEE.STD_LOGIC_1164.all ; entity encoder is port( x : in std_
我在我的游戏服务器中使用这些文件,每次我添加一个新的玩家模型时,我都会得到 [ERROR] lua/autorun/server/fastdlskins.lua:938: '' expected ne
我正在尝试更新我的 sqlite3 数据库,但出现此错误。我能够成功地将数据插入同一数据库,但无法更新它。请帮忙。 [SQLITE_ERROR] SQL error or missing databa
我想在通知区域旁边显示一个小弹出窗口。它类似于 Outlook/Skype/Live! Messenger/etc 在显示有关新消息的通知时会执行此操作。在我的例子中,它将有一些输入控件(文本框、日期
我正在尝试编写简单的程序以使用 gorp 将行插入表中,但在创建表时出现错误。 代码如下: package main import _ "github.com/mattn/go-sqlite3" im
我正在尝试运行工作目录中的 Octave 文件,但出现错误。 Octave 似乎没有认识到它应该运行该文件。 unknown@unknown> dir .
我正在尝试编写一些代码来模拟具有两个三态缓冲器和VHDL中的上拉电阻的电路。下面是我的代码: library ieee; use ieee.std_logic_1164.all; entity Pul
你能好心告诉我这里出了什么问题吗? conn 是 DriverManager.getConnection(DB_URL) try { PreparedState
我想在go中创建一个事务,同时这样做会出现错误:near "SET": syntax error。代码: db.Exec("SET TRANSACTION ISOLATION LEVEL REPEAT
所以我想用这样的颜色可视化一个矩阵 library(RColorBrewer) vec = rbinom(10000,1,0.1) n = sum(vec) vec = ifelse(vec == 1
private static final String QUERY = "SELECT * FROM " + TABLE_SONG_DETAILS + " WHERE " + TABLE_SONG_D
希望大家一切都好。 我正在尝试创建一个 mysql 触发器,但是我不断收到以下错误: [Err] 1064 - You have an error in your SQL syntax; check
我是一名优秀的程序员,十分优秀!