java - 如何通过 json 数据以编程方式在谷歌地图中添加最近的标记
问题描述
我对堆栈和 Android 相当陌生,需要一些帮助,通过带有 JSON 数据的 android 代码添加最近的标记,在 JSON 中通过 lat 和 lon。我在页面上显示了商店信息,我只是不知道如何在地图上添加标记。任何帮助将不胜感激
我的代码如下:
package com.example.mdona.maptest;
import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.GradientDrawable;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.renderscript.Double3;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.google.android.gms.maps.MapFragment;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;
import static java.lang.Double.valueOf;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private static JsonNinja jninja = new JsonNinja();
private static String API_KEY ="MDpmNWI1YTdkYS1lNDNhLTExZTgtOTE1Yy02ZjczZWQ0ZmIxM2M6dkJad1htQW56TUtNMWRDSzJISjZoVjU3bzFRNE9GREdHT1ZK";
private ArrayList<String> address_final = new ArrayList<>();
private ArrayList<String> storeLat = new ArrayList<>();
private ArrayList<String> storeLon = new ArrayList<>();
private ArrayList<String> city = new ArrayList<>();
private ArrayList<String> telephone = new ArrayList<>();
private ArrayList<String> quantity = new ArrayList<>();
String product_id;
double latitude;
double longitude;
LinearLayout NearestLocation;
GoogleMap mGoogleMap;
SupportMapFragment mapFrag;
LocationRequest mLocationRequest;
Location mLastLocation;
Marker mCurrLocationMarker;
FusedLocationProviderClient mFusedLocationClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFrag = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
NearestLocation = findViewById(R.id.nearest_location);
}
@Override
public void onPause() {
super.onPause();
if (mFusedLocationClient != null) {
mFusedLocationClient.removeLocationUpdates(mLocationCallback);
}
}
@Override
public void onMapReady(GoogleMap googleMap) {
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000);
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
else {
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
List<Location> locationList = locationResult.getLocations();
if (locationList.size() > 0) {
Location location = locationList.get(locationList.size() - 1);
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
getLatitude();
getLongitude();
getUserStoreLocInv("311787", latitude, longitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 11));
}
}
};
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(this)
.setTitle("Location Permission Needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION );
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mGoogleMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permission denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
public double getLatitude() {
if (mLastLocation != null) {
latitude = mLastLocation.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (mLastLocation != null) {
longitude = mLastLocation.getLongitude();
}
return longitude;
}
public void getUserStoreLocInv(String product_id, double lat, double lon) {
AsyncHttpClient client = new AsyncHttpClient();
client.addHeader("Authorization", API_KEY);
client.addHeader("Accept", "application/json");
client.get("http://lcboapi.com/stores?lat=" + lat + "&lon=" + lon + "&product_id=" + product_id + "&per_page=5", new AsyncHttpResponseHandler() {
//====================================>>
//=========== SUCCESS =============>>
@Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody) {
Log.e("Success", "Yes!");
String converted_string = new String(responseBody);
jninja.NinjaParse(converted_string);
ArrayList<String> names = jninja.GetNames();
ArrayList<String> vals = jninja.GetVals();
for (int i = 0; i < vals.size(); i++) {
if (names.get(i).equals("address_line_1")) {
address_final.add(vals.get(i).replace("\"",""));
}
if (names.get(i).equals("city")) {
city.add(vals.get(i).replace("\"",""));
}
if (names.get(i).equals("telephone")) {
telephone.add(vals.get(i).replace("\"",""));
}
if (names.get(i).equals("quantity")) {
quantity.add(vals.get(i));
}
if (names.get(i).equals("latitude")) {
storeLat.add(vals.get(i));
}
if (names.get(i).equals("longitude")) {
storeLon.add(vals.get(i));
}
}
CreateStoreAddress(address_final, city, telephone, quantity);
}
@Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, byte[] responseBody, Throwable error) {
Log.e("Fail", "No!");
}
});
}
public void CreateStoreAddress(ArrayList<String> address_final, ArrayList<String> city, ArrayList<String> telephone,
ArrayList<String> quantity)
{
Point size = new Point();
getWindowManager().getDefaultDisplay().getSize(size);
int screenWidth = size.x;
for (int i = 0; i < address_final.size(); i++) {
LinearLayout addressCompleteLayout = new LinearLayout(this);
LinearLayout addressLayout = new LinearLayout(this);
LinearLayout cityLayout = new LinearLayout(this);
LinearLayout telephoneLayout = new LinearLayout(this);
LinearLayout quantityLayout = new LinearLayout(this);
GradientDrawable border = new GradientDrawable();
border.setStroke(3, Color.BLACK);
border.setSize(screenWidth, 100);
TextView address = new TextView(this);
TextView city_loc = new TextView(this);
TextView phone = new TextView(this);
TextView amount = new TextView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(20,20,20,20);
addressCompleteLayout.setLayoutParams(params);
addressCompleteLayout.setOrientation(LinearLayout.VERTICAL);
addressCompleteLayout.setBackground(border);
NearestLocation.addView(addressCompleteLayout);
addressLayout.setLayoutParams(params);
addressLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(addressLayout);
cityLayout.setLayoutParams(params);
cityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(cityLayout);
telephoneLayout.setLayoutParams(params);
telephoneLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(telephoneLayout);
quantityLayout.setLayoutParams(params);
quantityLayout.setOrientation(LinearLayout.HORIZONTAL);
addressCompleteLayout.addView(quantityLayout);
address.setLayoutParams(params);
address.setText("Address: " + address_final.get(i));
addressLayout.addView(address);
city_loc.setLayoutParams(params);
city_loc.setText("City: " + city.get(i));
cityLayout.addView(city_loc);
amount.setLayoutParams(params);
amount.setText("Quantity Available: " + quantity.get(i));
quantityLayout.addView(amount);
phone.setLayoutParams(params);
phone.setText("Phone #: " + telephone.get(i));
telephoneLayout.addView(phone);
}
}
}
解决方案
因此,创建标记的方法是将以下内容添加到onMapReady
:
final LatLng coordinates= new LatLng(35, 35);
Marker Options myMarker= new MarkerOptions().position(coordinates).title("Location").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
mGoogleMap.addMarker(myMarker);
这会在您的地图上添加一个标记。现在,您可以35
用 json 文件中的坐标替换 。我希望这回答了你的问题。
推荐阅读
- angular - Angular,自动创建用户页面
- reactjs - 如何在 Next.js 中设置全局上下文而不会出现“文本内容不匹配”错误?
- html - 可拖动的 div 变得模糊取决于大小
- html - 如何使用引导程序将卡片右侧的内容定位到图像下方?
- javascript - 切换菜单问题
- python - 在scrapy csv文件中保留前导零
- haskell - 是什么导致我的程序只打印括号?
- tensorflow - 为什么 tensorflow repos 中使用了很多 tensorflow.python.xx API
- assembly - 在汇编中连接两个字符串
- c++ - 将元素分配给映射值时的C ++错误访问