4

mySQL データベースから Google マップ v2 にマーカーを作成しようとしていますが、うまくいきません。マップは表示されますが、マーカーはありません。何が間違っていて、何を変更する必要があるか教えてもらえますか? また、getDouble を getDouble(0) と getDouble(1) にしようとしましたが、どこかで 0 と 2 を試してみました。また、試した複数のチュートリアルからのインポートもたくさんあります。後で削除します。

マイ アクティビティ

com.google.android.gms.common.ConnectionResult をインポートします。

import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
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.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;

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


public class ReadComments extends FragmentActivity {
    private static final String LOG_TAG = "JsOn ErRoR";

    private static final String SERVICE_URL = "my url";

    protected GoogleMap mapB;

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

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

    private void setUpMapIfNeeded() {
        if (mapB == null) {
            mapB = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapB))
                    .getMap();
            if (mapB != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {

        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveAndAddCities();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive cities", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveAndAddCities() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        // Must run this on the UI thread since it's a UI operation.
        runOnUiThread(new Runnable() {
            public void run() {
                try {
                    createMarkersFromJson(json.toString());
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    void createMarkersFromJson(String json) throws JSONException {

        JSONArray jsonArray = new JSONArray(json);

        List<Marker> markers = new ArrayList<Marker>();

        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject jsonObj = jsonArray.getJSONObject(i);
            Marker marker = mapB.addMarker(new MarkerOptions()
                .title(jsonObj.getString("business_name"))
                .position(new LatLng(
                        jsonObj.getJSONArray("latlng").getDouble(0),
                        jsonObj.getJSONArray("latlng").getDouble(2)
                 ))
            );
            markers.add(marker);
        }
    }
}

URL からの JSON 出力

    [{"business_name":"Wine Bar","latlng":["43.6894658949280400","-116.3533687591552700"],
"business_id":"2","distance":"23.0298400562551"},
{"business_name":"Apple Headquarters","latlng":["37.3324083200000000","-122.0304781500000000"],
"business_id":"3","distance":"23.0298400562551"}]

私のLogcat(ログキャット全体をプルする方法はわかりませんが、これらはエラーです)

08-21 00:00:27.371: E/JsOn ErRoR(357):  at com..ReadComments.createMarkersFromJson(ReadComments.java:127)
08-21 00:00:27.371: E/JsOn ErRoR(357):  at com..ReadComments$2.run(ReadComments.java:107)

部分的なスクリーンショット

部分的なスクリーンショット

4

1 に答える 1

2

ここに正しいコードがあり、完璧に機能しています。修正してからいじっていたので、現在の場所にも移動するように更新されました。

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
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 android.app.Dialog;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;


public class GetLocalBus extends FragmentActivity implements LocationListener {
    private static final String LOG_TAG = "JsOn ErRoR";

    private static final String SERVICE_URL = "";

    protected GoogleMap mapB;

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

     // Getting Google Play availability status
        int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext());

        // Showing status
        if(status!=ConnectionResult.SUCCESS){ // Google Play Services are not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available   

            // Getting reference to the SupportMapFragment of activity_main.xml
            SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapB);

            // Getting GoogleMap object from the fragment
            mapB = fm.getMap();

            // Enabling MyLocation Layer of Google Map
            mapB.setMyLocationEnabled(true); 



             // Getting LocationManager object from System Service LOCATION_SERVICE
            LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve provider
            Criteria criteria = new Criteria();

            // Getting the name of the best provider
            String provider = locationManager.getBestProvider(criteria, true);

            // Getting Current Location
            Location location = locationManager.getLastKnownLocation(provider);

            if(location!=null){
                    onLocationChanged(location);
            }

            locationManager.requestLocationUpdates(provider, 20000, 0, this);
        }
    }

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

    private void setUpMapIfNeeded() {
        if (mapB == null) {
            mapB = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.mapB))
                    .getMap();
            if (mapB != null) {
                setUpMap();
            }
        }
    }

    private void setUpMap() {

        new Thread(new Runnable() {
            public void run() {
                try {
                    retrieveAndAddCities();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive cities", e);
                    return;
                }
            }
        }).start();
    }

    protected void retrieveAndAddCities() throws IOException {
        HttpURLConnection conn = null;
        final StringBuilder json = new StringBuilder();
        try {
            // Connect to the web service
            URL url = new URL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReader in = new InputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilder
            int read;
            char[] buff = new char[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            throw new IOException("Error connecting to service", e);
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }

        // Must run this on the UI thread since it's a UI operation.
        runOnUiThread(new Runnable() {
            public void run() {
                try {
                    createMarkersFromJson(json.toString());
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    void createMarkersFromJson(String json) throws JSONException {

        JSONArray jsonArray = new JSONArray(json);
        System.out.print(json);
        List<Marker> markers = new ArrayList<Marker>();

        for (int i = 0; i < jsonArray.length(); i++) {

            JSONObject jsonObj = jsonArray.getJSONObject(i);
            System.out.print(jsonObj.getJSONArray("latlng"));
            Marker marker = mapB.addMarker(new MarkerOptions()
                .title(jsonObj.getString("business_name"))
                .position(new LatLng(
                        jsonObj.getJSONArray("latlng").getDouble(0),
                        jsonObj.getJSONArray("latlng").getDouble(1)))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.graphic_map_icon))
            );
            markers.add(marker);
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        // Getting latitude of the current location
        double latitude = location.getLatitude();

        // Getting longitude of the current location
        double longitude = location.getLongitude();     

        // Creating a LatLng object for the current location
        LatLng latLng = new LatLng(latitude, longitude);

        // Showing the current location in Google Map
        mapB.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        // Zoom in the Google Map
        mapB.animateCamera(CameraUpdateFactory.zoomTo(15));

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}

ここにもPHPがあります

<?php




    if
    (isset($_GET['lat']) && isset($_GET['lon'])&& isset($_GET['dist'])){



    //make a simple database connection
        $db = new mysqli();



     $lat = $_GET['lat'];

         $lon = $_GET['lon'];

         $dist = $_GET['dist'];




        $search_sql = "SELECT business_id, business_name, CONCAT_WS(\",\",business_lat, business_lon) AS latlng, ( 3959 * acos( cos( radians(37) ) * cos( radians( " . $lat . " ) ) * cos( radians( " . $lon . " ) - radians(-122) ) + sin( radians(37) ) * sin( radians( " . $lat . " ) ) ) ) AS distance

                        FROM somewhere HAVING distance < " . $dist . " ORDER BY distance LIMIT 0 , 20";






        $search_results = $db->query($search_sql);



        if($search_results->num_rows){



     while ($row = $search_results->fetch_assoc())
{
    $return_data[] = array(
                            'business_name' => $row['business_name'],
                            'latlng'        => explode(',', $row['latlng']),
                            'business_id'   => $row['business_id'],
                            'distance'      => $row['distance']
                            );
}//end while


        }

        else{

            $return_data[] = array();

        }//end if




        }else{


        $return_data[] = array();

    }



    $bd_json = json_encode($return_data);



    $db->close();



    echo $bd_json;





?>

xml レイアウト

    <fragment android:id="@+id/mapB" 
        android:layout_width="fill_parent" 
        android:layout_height="250.0dip" 
        android:layout_alignParentTop="true" 
        android:layout_centerInParent="true" 
        class="com.google.android.gms.maps.SupportMapFragment"
        xmlns:android="http://schemas.android.com/apk/res/android" />

    <TextView 
        android:id="@+id/TextView1" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_below="@+id/mapB" />
</RelativeLayout>
于 2013-08-27T08:44:22.103 に答える