gpt4 book ai didi

android - 从外部 JSON 中获取谷歌地图标记

转载 作者:搜寻专家 更新时间:2023-11-01 08:03:39 26 4
gpt4 key购买 nike

我正在为 android (Google Maps API 2) 开发一个 map 应用程序,我的目标有两个。在那里,其中一些我设法做到了。

1:居中并跟随用户的位置。 (成功的)2:从外部JSON源获取标记并显示在 map 上。以及不断更新他们的位置。

我在这里找到了一段代码:https://gist.github.com/saxman/5347195

我将代码与来自 1 的代码放在一起。功能 1 仍然有效,但 logcat 说找不到我指定的文件。那是因为它不存在。我不知道 JSON 结构应该是什么样子,在服务器端启用 CORS 来获取 JSON 应该不会有任何危险。

但是,我想知道有没有人知道JSON结构应该是什么样子,因为我不知道如何弄清楚。此外,也许这段代码不起作用,因此如果 JSON 结构完整但标记没有出现,则可以更新问题,例如。

JSON 会是什么样子?我不可能弄清楚。

主 Activity .java

package com.billstrom.yolo;

import android.annotation.TargetApi;
import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.widget.TextView;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
*
*/

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class MainActivity extends FragmentActivity implements LocationListener {

private static final String LOG_TAG = "Example";

private static final String SERVICE_URL = "http://codele.se/app/blackcab/drivers.json";

protected GoogleMap map;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();

// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

// Showing status
if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
dialog.show();

}else { // Google Play Services are available

// Getting reference to the SupportMapFragment of activity_main.xml
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

// Getting GoogleMap object from the fragment
map = fm.getMap();

// Enabling MyLocation Layer of Google Map
map.setMyLocationEnabled(true);



// Getting LocationManager object from System Service LOCATION_SERVICE
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Creating a criteria object to retrieve provider
Criteria criteria = new Criteria();

// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);

// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);

if(location!=null){
onLocationChanged(location);
}

locationManager.requestLocationUpdates(provider, 20000, 0, this);
}

}

@Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
}

private void setUpMapIfNeeded() {
if (map == null) {
map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
.getMap();
if (map != null) {
setUpMap();
}
}
}
private void setUpMap() {
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveAndAddCities();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive cities", e);
return;
}
}
}).start();
}

protected void retrieveAndAddCities() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL(SERVICE_URL);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());

// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (IOException e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
} finally {
if (conn != null) {
conn.disconnect();
}
}

// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
runOnUiThread(new Runnable() {
public void run() {
try {
createMarkersFromJson(json.toString());
} catch (JSONException e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}

void createMarkersFromJson(String json) throws JSONException {
// De-serialize the JSON string into an array of city objects
JSONArray jsonArray = new JSONArray(json);
for (int i = 0; i < jsonArray.length(); i++) {
// Create a marker for each city in the JSON data.
JSONObject jsonObj = jsonArray.getJSONObject(i);
map.addMarker(new MarkerOptions()
.title(jsonObj.getString("name"))
.snippet(Integer.toString(jsonObj.getInt("population")))
.position(new LatLng(
jsonObj.getJSONArray("latlng").getDouble(0),
jsonObj.getJSONArray("latlng").getDouble(1)
))
);
}
}

@Override
public void onLocationChanged(Location location) {

TextView tvLocation = (TextView) findViewById(R.id.tv_location);

// Getting latitude of the current location
double latitude = location.getLatitude();

// Getting longitude of the current location
double longitude = location.getLongitude();

// Creating a LatLng object for the current location
LatLng latLng = new LatLng(latitude, longitude);

// Showing the current location in Google Map
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));

// Zoom in the Google Map
map.animateCamera(CameraUpdateFactory.zoomTo(15));


// Setting latitude and longitude in the TextView tv_location
tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude );

}

@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}

日志输出

07-01 16:27:40.787: E/Black Cab(17968): Error connecting to service
07-01 16:27:40.787: E/Black Cab(17968): java.io.FileNotFoundException: http://codele.se/app/blackcab/drivers.json
07-01 16:27:40.787: E/Black Cab(17968): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
07-01 16:27:40.787: E/Black Cab(17968): at com.billstrom.yolo.MainActivity.retrieveAndAddCities(MainActivity.java:133)
07-01 16:27:40.787: E/Black Cab(17968): at com.billstrom.yolo.MainActivity$1.run(MainActivity.java:117)
07-01 16:27:40.787: E/Black Cab(17968): at java.lang.Thread.run(Thread.java:856)
07-01 16:27:40.787: E/Black Cab(17968): Cannot retrive cities
07-01 16:27:40.787: E/Black Cab(17968): java.io.IOException: Error connecting to service
07-01 16:27:40.787: E/Black Cab(17968): at com.billstrom.yolo.MainActivity.retrieveAndAddCities(MainActivity.java:143)
07-01 16:27:40.787: E/Black Cab(17968): at com.billstrom.yolo.MainActivity$1.run(MainActivity.java:117)
07-01 16:27:40.787: E/Black Cab(17968): at java.lang.Thread.run(Thread.java:856)
07-01 16:27:40.787: E/Black Cab(17968): Caused by: java.io.FileNotFoundException: http://codele.se/app/blackcab/drivers.json
07-01 16:27:40.787: E/Black Cab(17968): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:186)
07-01 16:27:40.787: E/Black Cab(17968): at com.billstrom.yolo.MainActivity.retrieveAndAddCities(MainActivity.java:133)
07-01 16:27:40.787: E/Black Cab(17968): ... 2 more

最佳答案

最终答案:

首先,作为建议,Json在 Java 中真的很容易使用,特别是如果你使用 mapper .因此,不要担心如何使您的服务器端数据与您在其他地方找到的代码示例完美匹配 - 在客户端更改内容确实要容易得多。

记得给catch FileNotFoundException。如果将来出现问题,即使在修复了您的页面之后,它也会被抛出并使您的应用程序崩溃。我个人不喜欢那个特定的客户这样做,我更喜欢自己处理状态代码。永远不要假设在 QA 中有效的 HTTP 通信在生产中会随着时间的推移保持完美:保持防御。

在所有这些条件之后,您的 json 可能看起来像:[{"name": "bobbins driver", "latlng": [90, 180], "population": "012345"}, { "name": "barbara", "latlng": [0, -180], "population": "65432"}...].

请参阅docs LatLng 是什么。

至于你的跟进,这个话题太宽泛了。现在,使用 latlng 参数对 map 图 block 进行多次请求,并让您的服务器仅发送附近的图 block 。随着事情变得越来越有趣,如果你需要实时更新,有一些为此设计的协议(protocol),或者你可以使用具有高瓦片刷新率的谷歌地图“瓦片服务器”模式 - 0 UrlTileProvider一开始,或者这可能是 future 的 SO 问题。

祝你好运。

关于android - 从外部 JSON 中获取谷歌地图标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17407399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com