如何使用带有 json 的 Map 从数据库中设置地图 latlng 值?
Posted
技术标签:
【中文标题】如何使用带有 json 的 Map 从数据库中设置地图 latlng 值?【英文标题】:how using Map with json to set map latlng value from database? 【发布时间】:2018-03-20 16:18:51 【问题描述】:我尝试使用 json 从数据库中设置纬度和经度值来解析从 php 返回的响应 在函数 setmMap 我解析 json 和 woking 会!我单独测试了它并且工作! 在mapReady上我调用setmMap()并使用日志来测试日志打印map1和map2而不是打印map3这意味着不进入forloop如何让它进入 谢谢
package com.example.lef.firstapplication;
import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,GoogleMap.OnMarkerClickListener
private GoogleMap mMap;
private static final LatLng PERTH = new LatLng(-31.952854, 115.857342);
private static final LatLng SYDNEY = new LatLng(-33.87365, 151.20689);
private static final LatLng BRISBANE = new LatLng(-27.47093, 153.0235);
private Marker mPerth;
private Marker mSydney;
private Marker mBrisbane;
RequestQueue requestQueue;
String allFriend = "http://192.168.0.103/PlaneEye/v1/allFriend";
int friend_id;
String friend_Fname;
String friend_Lname;
double latitude;
double longitude;
LinearLayout info ;
TextView title ;
Button button;
TextView snippet;
public List <User> userInf=new ArrayList<>();
public List <User> friendList=new ArrayList<>();
public List<User> getUserInf()
return userInf;
public void setUserInf(List<User> userInf)
this.userInf = userInf;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
info = new LinearLayout(this);
title = new TextView(this);
snippet = new TextView(this);
button = new Button(this);
// prepareFriendsLocation();
info.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
button.setBackgroundColor(Color.WHITE);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
prepareFriendsList();
public void setmMap()
Log.w("test","map1");
friendList=prepareFriendsList();
Log.w("test","map2");
for (int i=0;i<friendList.size();i++)
Log.w("test","map3");
mMap.addMarker(new MarkerOptions()
.position(new LatLng(friendList.get(i).getLatitude(),friendList.get(i).getLongitude()))
.title(friendList.get(i).getfName()+friendList.get(i).getlName())
.snippet("(-27.47093,153.0235)")
.icon(BitmapDescriptorFactory.fromResource(R.drawable.friends_on_map))).setTag(0);
Log.w("jk",friendList.get(i).getfName()+friendList.get(i).getlName()+"yarb b2a");
mMap.setOnMarkerClickListener(this);
//getCompleteAddressString(-27.47093,153.0235);
//change markerInfoWindow style
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter()
@Override
public View getInfoWindow(Marker arg0)
return null;
@Override
public View getInfoContents(Marker marker)
info.setOrientation(LinearLayout.VERTICAL);
title.setTextColor(Color.BLACK);
title.setGravity(Gravity.CENTER);
title.setTypeface(null, Typeface.BOLD);
title.setText(marker.getTitle());
button.setText("Send Message");
snippet.setTextColor(Color.GRAY);
snippet.setText(marker.getSnippet());
info.removeView(title);
info.addView(title);
info.removeView(snippet);
info.addView(snippet);
info.removeView(button);
info.addView(button);
return info;
);
private List prepareFriendsList()
requestQueue = Volley.newRequestQueue(this);
StringRequest request=new StringRequest(Request.Method.POST, "http://192.168.0.103/PlaneEye/v1/allFriend", new Response.Listener<String>()
@Override
public void onResponse(String response)
try
JSONObject user = new JSONObject(response);
JSONArray friends=user.getJSONArray("users");
for (int i = 0; i <friends.length() ; i++)
final JSONObject friend = friends.getJSONObject(i);
friend_id = friend.getInt("user_id");
friend_Fname = friend.getString("fName");
friend_Lname = friend.getString("lName");
latitude = friend.getDouble("latitude");
longitude = friend.getDouble("longitude");
int online = friend.getInt("online");
userInf.add(new User(friend_id,friend_Fname,friend_Lname,latitude,longitude,online));
setUserInf(userInf);
catch (JSONException e)
, new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
Log.d("userData", "Error");
);
requestQueue.add(request);
return getUserInf();
@Override
public void onMapReady(GoogleMap map)
mMap = map;
// Add markers to the map
setmMap();
@Override
//CLick setOnMarkerClickListener
public boolean onMarkerClick(final Marker marker)
// Retrieve the data from the marker.
Integer clickCount = (Integer) marker.getTag();
// Check if a click count was set, then display the click count.
if (clickCount != null)
clickCount = clickCount + 1;
marker.setTag(clickCount);
Toast.makeText(this,
marker.getTitle() +
" has been clicked " + clickCount + " times.",
Toast.LENGTH_SHORT).show();
return false;
//get the location from lattude logtude
private String getCompleteAddressString(double LATITUDE, double LONGITUDE)
String strAdd = "";
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
try
List<android.location.Address> addresses =
geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
if(Geocoder.isPresent())
if (addresses != null)
android.location.Address returnedAddress =addresses.get(0);
StringBuilder strReturnedAddress = new StringBuilder("");
for (int i = 0; i <= returnedAddress.getMaxAddressLineIndex(); i++)
strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
strAdd = strReturnedAddress.toString();
else
//strAdd = "unfortunately, we can't display address Now";
else
Log.w("error","false");
catch (Exception e)
e.printStackTrace();
//strAdd = "Please check your internet connection";
return strAdd;
【问题讨论】:
使用 http req/res 时需要异步思考。friendList
为空,因为请求仍在进行中。也许在请求的“onResponse”函数中设置地图对象。
在凌空返回响应后调用你的setmMap
方法,你正在使用异步凌空请求
如何做到这一点?
【参考方案1】:
这可以更好地构建,但这里有一个来自您的代码的示例来帮助您开始。
private void prepareFriendsList()
requestQueue = Volley.newRequestQueue(this);
StringRequest request=new StringRequest(Request.Method.POST,
"http://192.168.0.103/PlaneEye/v1/allFriend",
new Response.Listener<String>()
@Override
public void onResponse(String response)
try
List<User> users = new ArrayList<>();
JSONObject user = new JSONObject(response);
JSONArray friends=user.getJSONArray("users");
for (int i = 0; i <friends.length() ; i++)
final JSONObject friend = friends.getJSONObject(i);
friend_id = friend.getInt("user_id");
friend_Fname = friend.getString("fName");
friend_Lname = friend.getString("lName");
latitude = friend.getDouble("latitude");
longitude = friend.getDouble("longitude");
int online = friend.getInt("online");
users.add(new User(friend_id,friend_Fname,friend_Lname,latitude,longitude,online));
//setUserInf(userInf); // Dont update the entire list every iteration.
Log.d("Users parsed, call back to set Users!");
setUserInf(users);
catch (JSONException e)
,
new Response.ErrorListener()
@Override
public void onErrorResponse(VolleyError error)
Log.d("userData", "Error");
);
requestQueue.add(request);
Log.d("Request Sent!");
//return getUserInf(); // empty list since users not parsed yet
然后更改 setUserInf 这是异步响应准备好时的回调。使用此函数构建地图对象。
public void setUserInf(List<User> users)
this.userInf = users;
Log.d("Response callback!!");
for (int i=0;i<friendList.size();i++)
mMap.addMarker(new MarkerOptions() ...
...
这将为您提供您所期望的流程。
> Request Sent!
> //... other logs while waiting for response.
> Users parsed, call back to set Users!
> Response callback!!
【讨论】:
监视器中打印的唯一消息是“请求已发送!” @RanaTarek “userData 错误”怎么样?那是截击中的另一个听众。以上是关于如何使用带有 json 的 Map 从数据库中设置地图 latlng 值?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Azure Synapse 或数据工厂管道中设置和获取变量值
Freemarker:创建下拉字段并从 Map 的键/值中设置其值和选项