Skip to content Skip to sidebar Skip to footer

Create Markers From Json Array Php Mysql Google Maps V2 Android

I'm trying to create markers on Google Maps v2 from my mySQL database and it is not working. The map does come up but there are no markers. Can any one tell me what is wrong and wh

Solution 1:

I've Got the right code here its working perfect. it has been updated to go to the current location as well because I've been messing with it since the fix.

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;


publicclassGetLocalBusextendsFragmentActivityimplementsLocationListener {
    privatestaticfinalStringLOG_TAG="JsOn ErRoR";

    privatestaticfinalStringSERVICE_URL="";

    protected GoogleMap mapB;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.get_local);
        setUpMapIfNeeded();

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

        // Showing statusif(status!=ConnectionResult.SUCCESS){ // Google Play Services are not availableintrequestCode=10;
            Dialogdialog= GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
            dialog.show();

        }else { // Google Play Services are available   // Getting reference to the SupportMapFragment of activity_main.xmlSupportMapFragmentfm= (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_SERVICELocationManagerlocationManager= (LocationManager) getSystemService(LOCATION_SERVICE);

            // Creating a criteria object to retrieve providerCriteriacriteria=newCriteria();

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

            // Getting Current LocationLocationlocation= locationManager.getLastKnownLocation(provider);

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

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

    @OverrideprotectedvoidonResume() {
        super.onResume();
        setUpMapIfNeeded();
    }

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

    privatevoidsetUpMap() {

        newThread(newRunnable() {
            publicvoidrun() {
                try {
                    retrieveAndAddCities();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Cannot retrive cities", e);
                    return;
                }
            }
        }).start();
    }

    protectedvoidretrieveAndAddCities()throws IOException {
        HttpURLConnectionconn=null;
        finalStringBuilderjson=newStringBuilder();
        try {
            // Connect to the web serviceURLurl=newURL(SERVICE_URL);
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReaderin=newInputStreamReader(conn.getInputStream());

            // Read the JSON data into the StringBuilderint read;
            char[] buff = newchar[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error connecting to service", e);
            thrownewIOException("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(newRunnable() {
            publicvoidrun() {
                try {
                    createMarkersFromJson(json.toString());
                } catch (JSONException e) {
                    Log.e(LOG_TAG, "Error processing JSON", e);
                }
            }
        });
    }

    voidcreateMarkersFromJson(String json)throws JSONException {

        JSONArrayjsonArray=newJSONArray(json);
        System.out.print(json);
        List<Marker> markers = newArrayList<Marker>();

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

            JSONObjectjsonObj= jsonArray.getJSONObject(i);
            System.out.print(jsonObj.getJSONArray("latlng"));
            Markermarker= mapB.addMarker(newMarkerOptions()
                .title(jsonObj.getString("business_name"))
                .position(newLatLng(
                        jsonObj.getJSONArray("latlng").getDouble(0),
                        jsonObj.getJSONArray("latlng").getDouble(1)))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.graphic_map_icon))
            );
            markers.add(marker);
        }
    }

    @OverridepublicvoidonLocationChanged(Location location) {
        // Getting latitude of the current locationdoublelatitude= location.getLatitude();

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

        // Creating a LatLng object for the current locationLatLnglatLng=newLatLng(latitude, longitude);

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

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

    }

    @OverridepublicvoidonProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @OverridepublicvoidonProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @OverridepublicvoidonStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }
}

Also here is the PHP

<?phpif
    (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 layout

<fragmentandroid: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" /><TextViewandroid:id="@+id/TextView1"android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_below="@+id/mapB" /></RelativeLayout>

Post a Comment for "Create Markers From Json Array Php Mysql Google Maps V2 Android"