自定义谷歌地图标记为Android添加按钮在信息窗口

时间:2017-04-07 06:31:51

标签: android google-maps google-maps-android-api-2

我实际上正在尝试开发一个应用程序,我必须使用json解析在地图上绘制标记。我不知道自定义标记信息窗口,我想知道如何在信息窗口上添加一个按钮,以便我可以从标记的信息窗口跳转到另一个活动。这是我的代码,

public class MainActivity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener,OnMapReadyCallback , GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, View.OnClickListener {

SupportMapFragment sMapFragment;
public GoogleMap mMap;
private HttpURLConnection urlConnection = null;
private BufferedReader reader = null;
private String forecastJsonStr = null;
LoginActivity loginActivity;
private static final String TAG = "Mapsactivity";
SharedPreferences sharedPreferences;


//hereyes
double lat, lon;


//this url
private String url = "url";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    sMapFragment = SupportMapFragment.newInstance();
    loginActivity = new LoginActivity();

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    sMapFragment.getMapAsync(this);
    android.support.v4.app.FragmentManager sFM = getSupportFragmentManager();
    sFM.beginTransaction().add(R.id.Map, sMapFragment).commit();


    //sugesstion


    PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
            getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            // TODO: Get info about the selected place.

            try {
                String Placename = (String) place.getName();
                LatLng Placelat = place.getLatLng();
                double lat = Placelat.latitude;
                double lng = Placelat.longitude;




                String Searchlat=String.valueOf(lat);
                String SearchLog=String.valueOf(lng);
                SearchRequest(Searchlat,SearchLog);

                onMapSearch(Placename);

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


            Log.i(TAG, "Place: " + place.getName());
            //Log.i(TAG, "Lat: " + place.getLatLng());
        }

        @Override
        public void onError(Status status) {
            // TODO: Handle the error.
            Log.i(TAG, "An error occurred: " + status);
        }
    });

}
private void SearchRequest(final String latt, final String lonn) {
      //for Search Result

    class RetriveMarkerTask extends AsyncTask<String, Void, String> {
        private Context context;


        public RetriveMarkerTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            pd = new ProgressDialog(MainActivity.this);
            pd.setTitle("Please wait ...");
            pd.setMessage("Connecting to Loofre Network");
            pd.setCancelable(false);
            pd.show();


        }

        protected String doInBackground(String... markerGetUrl) {
            String llat=markerGetUrl[0];
            String llon=markerGetUrl[1];
            Log.d("lattt",llat); //ok let me run ok br
            if (android.os.Debug.isDebuggerConnected())
                android.os.Debug.waitForDebugger();

            try {

                double lat = 0;
                double lon = 0;
                double lat_asynch= Double.parseDouble(llat);
                double lon_asynch= Double.parseDouble(llon);
                GPSTracker gps = new GPSTracker(MainActivity.this);
                Log.d("trueee", String.valueOf(gps.canGetLocation()));
                // latitude = String.valueOf(gps.getLatitude());
                // longitude = String.valueOf(gps.getLongitude())

                int i = 0;

                String baseUrl = url;
                if (llat!= null) {
                    baseUrl += "&radius=5&latitude=" + String.valueOf(lat_asynch) + "&longitude=" + String.valueOf(lon_asynch);
                    Log.d("url", baseUrl);
                }
                URL dataURL = new URL(baseUrl);
                Log.d("urltotal", baseUrl);
                //radius=5&latitude=28.669880&longitude=77.141403
                //search this error in google

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

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a lot easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();
            } catch (IOException e) {
                Log.e("PlaceholderFragment", "Error ", e);
                forecastJsonStr = "Error, an exception was raised.";
            } finally {
                if (urlConnection != null) {

                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("PlaceholderFragment", "Error closing stream", e);
                    }
                }
            }
            return forecastJsonStr;
            //pase here

        }


        //on post execution For SearchResult

        protected void onPostExecute(String markers) {


            // for map Search
            Log.d("string response", markers);

            Toast.makeText(MainActivity.this, "Plotting Thekha", Toast.LENGTH_LONG).show();

            try {

                JSONArray jsonArray = new JSONArray(markers);
                for (int i = 0; i < jsonArray.length(); i++) {
                    //create marker of each place in the json data
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    final String placeName = jsonObject.getString("name");
                    String placeAddress = jsonObject.getString("address");
                    double latitude = jsonObject.getJSONArray("latlang").getDouble(0);
                    double longitude = jsonObject.getJSONArray("latlang").getDouble(1);
                    LatLng loc = new LatLng(latitude, longitude);
                    //marker size change code
                    int height = 150;
                    int width = 150;
                    BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.thekhaicon);
                    Bitmap b = bitmapDrawable.getBitmap();
                    Bitmap smallMarker = Bitmap.createScaledBitmap(b, width, height, false);
                    //marker size change code ends here
                    //mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 13));

                    mMap.addMarker(new MarkerOptions()
                            .icon(BitmapDescriptorFactory.fromBitmap(smallMarker))
                            .title(placeName)
                            .snippet(placeAddress)
                            .position(loc));


                }
                //marker size change code
                int height = 120;
                int width = 120;
                BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(R.drawable.iamhereicon);
                Bitmap b = bitmapDrawable.getBitmap();
                Bitmap youarehere = Bitmap.createScaledBitmap(b, width, height, false);
                LatLng point = new LatLng(Double.parseDouble(latt), Double.parseDouble(lonn));
                CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(point, 13);
                mMap.animateCamera(cameraUpdate);


                pd.dismiss();


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

        }
    }
    RetriveMarkerTask retriveMarkerTask=new RetriveMarkerTask(MainActivity.this);
    retriveMarkerTask.execute(latt,lonn);
}

0 个答案:

没有答案