我正在开发一个Android应用, 而我正试图在地图上显示json中的位置。
我很乐意提供帮助,谢谢。
city.json:
[{
"name": "test1",
"lat": 31.783306,
"lng": 34.980238
},
{
"name": "test2",
"lat": 31.432895,
"lng": 34.541314
}]
AlertView.java:
public class AlertView extends AppCompatActivity implements OnMapReadyCallback{
GoogleMap mMap;
String mAlertZone;
String mAlertDateString;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up UI
setContentView(R.layout.alert_view);
// Get map instance
//mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Initialize alert
unpackExtras();
// Initialize UI
initializeUI();
// Initialize map
initializeMap();
}
void unpackExtras() {
// Get alert area
mAlertZone = getIntent().getStringExtra(AlertViewParameters.ALERT_ZONE);
// Get alert date string
mAlertDateString = getIntent().getStringExtra(AlertViewParameters.ALERT_DATE_STRING);
}
void mapLoadedListener () {
// Wait for map to load
mMap.setOnCameraChangeListener(new GoogleMap.OnCameraChangeListener() {
@Override
public void onCameraChange(CameraPosition arg0) {
// Prevent from being called again
//mMap.setOnCameraChangeListener(null);
// Fix RTL bug with hebrew
mMap.setInfoWindowAdapter(new RTLMarkerInfoWindowAdapter(getLayoutInflater()));
// Show my location button
//mMap.setMyLocationEnabled(true);
// Wait for tiles to load
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// Add map overlays
addOverlays();
}
}, 500);
}
});
}
void initializeMap() {
// Get map instance
if (mMap == null) {
// Stop execution
return;
}
// Wait for map to load
addOverlays();
}
List<LatLng> values = new ArrayList<LatLng>();
void addOverlays() {
// Get alert area
List<City> cities = LocationData.getCitiesByZone(mAlertZone, this);
// No cities found?
if (cities.size() == 0) {
return;
}
// Default to zoom of 8
int zoom = 8;
// Default to center of Israel
LatLng location = new LatLng(31.4117256, 35.0818155);
// Get user's locale
boolean isEnglish = Localization.isEnglishLocale(this);
// Traverse over cities
for (City city : cities) {
// No location?
if (city.latitude == 0) {
continue;
}
// Get name
String cityName = (isEnglish) ? city.nameEnglish : city.name;
// Get countdown
String zoneWithCountdown = LocationData.getLocalizedZoneWithCountdown(city.zone, this);
// Set title manually after overriding locale
setTitle(zoneWithCountdown);
// Set zoom
zoom = 12;
// Create location
location = new LatLng(city.latitude, city.longitude);
values.add(location); //this adds an element to the list.
// Optional snippet
String snippet = null;
// Add shelter count if exists for this city
//if (city.shelters > 0) {
//snippet = getString(R.string.lifeshieldShelters) + " " + city.shelters;
//}
// Add marker to map
mMap.addMarker(new MarkerOptions()
.position(location)
.title(cityName)
.snippet(snippet));
}
// Prepare new camera position
CameraPosition position = new CameraPosition.Builder()
.target(location)
.zoom(zoom)
.tilt(30)
.bearing(10)
.build();
// Animate nicely
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(position), 1500, null);
aa();
}
void aa() {
if (values.size() > 1) {
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (LatLng c : values) {
builder.include(c);
}
LatLngBounds bounds = builder.build();
float zoomLevel = 16.0f; //This goes up to 21 // offset from edges of the map in pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, 320);
mMap.animateCamera(cu);
}
}
@Override
public boolean onCreateOptionsMenu(Menu OptionsMenu) {
// Add share button
initializeShareButton(OptionsMenu);
// Show the menu
return true;
}
private String getShareMessage() {
// Get zone name
String zone = LocationData.getLocalizedZone(mAlertZone, this);
// Construct share message
return getString(R.string.alertSoundedAt) + " " + zone + " (" + LocationData.getCityNamesByZone(mAlertZone, this) + ") " + getString(R.string.atTime) + " " + mAlertDateString + " " + getString(R.string.alertSentVia);
}
void initializeShareButton(Menu OptionsMenu) {
// Add refresh in Action Bar
MenuItem shareItem = OptionsMenu.add(Menu.NONE, Menu.NONE, Menu.NONE, getString(R.string.shareAlert));
// Set up the view
shareItem.setIcon(R.drawable.ic_share);
// Specify the show flags
MenuItemCompat.setShowAsAction(shareItem, MenuItem.SHOW_AS_ACTION_ALWAYS);
// On click, open share
shareItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
// Prepare share intent
Intent shareIntent = new Intent(Intent.ACTION_SEND);
// Set as text/plain
shareIntent.setType("text/plain");
// Add text
shareIntent.putExtra(Intent.EXTRA_TEXT, getShareMessage());
// Show chooser
startActivity(Intent.createChooser(shareIntent, getString(R.string.shareAlert)));
// Consume event
return true;
}
});
}
public boolean onOptionsItemSelected(final MenuItem Item) {
// Check item ID
switch (Item.getItemId()) {
// Home button?
case android.R.id.home:
onBackPressed();
}
return super.onOptionsItemSelected(Item);
}
@Override
protected void onResume() {
super.onResume();
// Support for RTL languages
RTLSupport.mirrorActionBar(this);
// Clear notifications and stop sound from playing
AppNotifications.clearAll(this);
}
@Override
public void onConfigurationChanged(android.content.res.Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Support for RTL languages
RTLSupport.mirrorActionBar(this);
}
void initializeUI() {
// Reset activity name (after localization is loaded)
setTitle(R.string.appName);
// Allow click on home button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// RTL action bar hack
RTLSupport.mirrorActionBar(this);
}
}
LocationData.java:
public class LocationData {
private static List<City> mCities;
public static List<City> getAllCities(Context context) {
// Got it in cache?
if (mCities != null) {
return mCities;
}
// Initialize the list
mCities = new ArrayList<>();
try {
// Open the cities.json for reading
InputStream stream = context.getResources().openRawResource(R.raw.cities);
// Create a buffered reader
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
// StringBuilder for efficiency
StringBuilder builder = new StringBuilder();
// A temporary variable to store current line
String currentLine;
// Read all lines
while ((currentLine = reader.readLine()) != null) {
// Append to builder
builder.append(currentLine);
}
// Convert to string
String json = builder.toString();
// Convert to city objects
mCities = Singleton.getJackson().readValue(json, new TypeReference<List<City>>() {
});
}
catch (Exception exc) {
// Log it
Log.e(Logging.TAG, "Failed to load cities.json", exc);
}
// Return them
return mCities;
}
}
City.java:
public class City {
@JsonProperty("lat")
public int latitude;
@JsonProperty("lng")
public int longitude;
@JsonProperty("name")
public String name;
@Override
public String toString() {
return value;
}
}
我尝试了一些操作,但是当我打开地图时,它在与json文件中所写位置不同的位置打开了地图。
答案 0 :(得分:1)
首先,您应该使用LatLng对象 喜欢,
new LatLng(latitude.doubleValue(), longtitude.doubleValue());
如果您决定不这样做,则至少应在城市等级中为纬度和经度使用双值。