如何同时从数据库中获取数据和使用地图

时间:2019-06-18 10:20:34

标签: java android dictionary marker

我们需要程序从数据库中获取数据(经度和纬度),并将具有这些坐标的标记添加到地图中

MapsActivity:

 package ilfarsif.myapp_places;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

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;

public class MapsActivity2 extends FragmentActivity {


private GoogleMap mMap; // Might be null if Google Play services APK is not available.

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

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

/**
 * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
 * installed) and the map has not already been instantiated.. This will ensure that we only ever
 * call {@link #setUpMap()} once when {@link #mMap} is not null.
 * <p/>
 * If it isn't installed {@link SupportMapFragment} (and
 * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
 * install/update the Google Play services APK on their device.
 * <p/>
 * A user can return to this FragmentActivity after following the prompt and correctly
 * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
 * have been completely destroyed during this process (it is likely that it would only be
 * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
 * method in {@link #onResume()} to guarantee that it will be called.
 */
private void setUpMapIfNeeded() {
    // Do a null check to confirm that we have not already instantiated the map.
    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            setUpMap();
        }
    }
}

/**
 * This is where we can add markers or lines, add listeners or move the camera. In this case, we
 * just add a marker near Africa.
 * <p/>
 * This should only be called once and when we are sure that {@link #mMap} is not null.
 */
private void setUpMap() {
    //mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
    String arrayUrl = "id[]=1&id[]=2&id[]=3&id[]=4";
    SuggestionAdapter sa = new SuggestionAdapter();
    sa.execute(arrayUrl);

}
}

SuggestionAdapter:

package ilfarsif.myapp_places;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Filter;

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.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

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

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class SuggestionAdapter extends AsyncTask<String, Void, String> {

    public static String LOG_TAG = "my_log";
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String resultJson = "";

@Override
protected String doInBackground(String... Params) {
    // получаем данные с внешнего ресурса

    try {
        String strUrl = "";
        if( Params.length > 0 ){
            strUrl = Params[0];
        }

        URL url = new URL("http://www.p89742wj.bget.ru/test3.php?"+ strUrl);//id[]=1&id[]=2&id[]=3

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        resultJson = buffer.toString();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultJson;
}

@Override
protected void onPostExecute(String strJson) {
    super.onPostExecute(strJson);
    // выводим целиком полученную json-строку
    Log.d(LOG_TAG, strJson);

    JSONObject dataJsonObj = null;
    String idByMagName = "";

    try {

        dataJsonObj = new JSONObject(strJson);

        //--
        JSONObject mag  = dataJsonObj.getJSONObject("idMag");
        idByMagName = mag.getString("idd");
        Log.d(LOG_TAG, "Дешевый Магазин: " + idByMagName);
        //--
        JSONArray products  = dataJsonObj.getJSONArray("Mag");
        for (int i = 0; i < products.length(); i++) {
            JSONObject obj = products.getJSONObject(i);
            String Id = obj.getString("id_mag");
            String Adress = obj.getString("adress");
            //String LL = obj.getString("latlng");
            String Lat=obj.getString("lat");
            String Lng=obj.getString("lng");

            double latitude = Double.parseDouble(Lat);//String LL ConvertTO LLDouble
            double longitude = Double.parseDouble(Lng);
            int iddd = Integer.parseInt(Id);
            int dii = Integer.parseInt(idByMagName);

            Log.d(LOG_TAG, "id: " + Id);
            Log.d(LOG_TAG, "adress: " + Adress);
            Log.d(LOG_TAG, "lat: " + Lat);
            Log.d(LOG_TAG, "lang: " + Lng);

           /* LatLng latLng_new = new LatLng(latitude, longitude);
            mMap.addMarker(new MarkerOptions().position(latLng_new).title("Marker 1"));*/








        }





    } catch (JSONException e) {
        e.printStackTrace();
    }
}

}

建议我们将此循环插入代码中,但无效。问题在于,mMap地图片段未在RecommendationionAdapter中定义,并且该代码无法在MapsActivity中工作

for (int i = 0; i < products.length(); i++) {
                JSONObject obj = products.getJSONObject(i);
                String Id = obj.getString("id_mag");
                String Adress = obj.getString("adress");
                //String LL = obj.getString("latlng");
                String Lat=obj.getString("lat");
                String Lng=obj.getString("lng");

                double latitude = Double.parseDouble(Lat);
//String LL ConvertTO LLDouble
                double longitude = Double.parseDouble(Lng);
                int iddd = Integer.parseInt(Id);
                int dii = Integer.parseInt(idByMagName);

              Marker melbourne = mMap.addMarker(new MarkerOptions()
                          .position(new LatLng(latitude , longitude))
                          .title("Melbourne")
                          .snippet("Population: 4,137,400"));
            }

0 个答案:

没有答案