Я пытаюсь применить приведенный ниже пример для моего собственного приложения.Чтобы добавить файл Geojson, я справился с другим кодом, но не смог заставить его работать с данными в реальном времени.Я просто хочу показать разные цвета в зависимости от состояния точки, чтобы принимать информацию в режиме реального времени.Первая проблема с кодом состоит в том, что он не запускает пример, имеет много ошибок.Вторая попытка привести его в меру моего приложения показывает некоторые дополнительные ошибки.Одной из ошибок является getmap (), который был заменен getmapAync, но это не решило проблему.Любые предложения для ошибок кода.Есть ли лучший способ добавить пространственные данные в реальном времени, не отслеживая информацию только статус из их свойств.
GeoJSON - отображение и стили данных GeoJSON
package com.example.testnavbar;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import com.google.maps.android.data.Feature;
import com.google.maps.android.data.geojson.GeoJsonFeature;
import com.google.maps.android.data.geojson.GeoJsonLayer;
import com.google.maps.android.data.geojson.GeoJsonLineString;
import com.google.maps.android.data.geojson.GeoJsonPointStyle;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext;
public class HomeFragment extends Fragment {
private final static String mLogTag = "GeoJson";
GoogleMap mGoogleMap;
MapView mMapView;
View mView;
/**
* Assigns a color based on the given magnitude
*/
private static float magnitudeToColor(double status) {
if (status == 1) {
return BitmapDescriptorFactory.HUE_GREEN;
} else if (status == 2) {
return BitmapDescriptorFactory.HUE_YELLOW;
} else {
return BitmapDescriptorFactory.HUE_RED;
}
}
protected int getLayoutId() {
return R.layout.activity_maps;
}
protected void startDemo() {
// Download the GeoJSON file.
retrieveFileFromUrl();
// Alternate approach of loading a local GeoJSON file.
//retrieveFileFromResource();
}
private void retrieveFileFromUrl() {
new DownloadGeoJsonFile().execute(getString(R.string.geojson_url));
}
private void retrieveFileFromResource() {
try {
GeoJsonLayer layer = new GeoJsonLayer(getMap(), R.raw.picnicsites, this);
addGeoJsonLayerToMap(layer);
} catch (IOException e) {
Log.e(mLogTag, "GeoJSON file could not be read");
} catch (JSONException e) {
Log.e(mLogTag, "GeoJSON file could not be converted to a JSONObject");
}
}
/**
* Adds a point style to all features to change the color of the marker based on its magnitude
* property
*/
private void addColorsToMarkers(GeoJsonLayer layer) {
// Iterate over all the features stored in the layer
for (GeoJsonFeature feature : layer.getFeatures()) {
// Check if the magnitude property exists
if (feature.getProperty("mag") != null && feature.hasProperty("place")) {
double magnitude = Double.parseDouble(feature.getProperty("mag"));
// Get the icon for the feature
BitmapDescriptor pointIcon = BitmapDescriptorFactory
.defaultMarker(magnitudeToColor(magnitude));
// Create a new point style
GeoJsonPointStyle pointStyle = new GeoJsonPointStyle();
// Set options for the point style
pointStyle.setIcon(pointIcon);
pointStyle.setTitle("Magnitude of " + magnitude);
pointStyle.setSnippet("Earthquake occured " + feature.getProperty("place"));
// Assign the point style to the feature
feature.setPointStyle(pointStyle);
}
}
}
private class DownloadGeoJsonFile extends AsyncTask<String, Void, GeoJsonLayer> {
@Override
protected GeoJsonLayer doInBackground(String... params) {
try {
// Open a stream from the URL
InputStream stream = new URL(params[0]).openStream();
String line;
StringBuilder result = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
while ((line = reader.readLine()) != null) {
// Read and save each line of the stream
result.append(line);
}
// Close the stream
reader.close();
stream.close();
return new GeoJsonLayer(getMap(), new JSONObject(result.toString()));
} catch (IOException e) {
Log.e(mLogTag, "GeoJSON file could not be read");
} catch (JSONException e) {
Log.e(mLogTag, "GeoJSON file could not be converted to a JSONObject");
}
return null;
}
@Override
protected void onPostExecute(GeoJsonLayer layer) {
if (layer != null) {
addGeoJsonLayerToMap(layer);
}
}
}
private void addGeoJsonLayerToMap(GeoJsonLayer layer) {
addColorsToMarkers(layer);
layer.addLayerToMap();
getMap().moveCamera(CameraUpdateFactory.newLatLng(new LatLng(35.126411,33.429859)));
// Demonstrate receiving features via GeoJsonLayer clicks.
layer.setOnFeatureClickListener(new GeoJsonLayer.GeoJsonOnFeatureClickListener() {
@Override
public void onFeatureClick(Feature feature) {
Toast.makeText(HomeFragment.this,
"Feature clicked: " + feature.getProperty("title"),
Toast.LENGTH_SHORT).show();
}
});
}
}