java - Google Maps V2 Android Doesnt Appears -
i've follow tutorial create simple android map, here's source code (mainactivity.java) :
package com.tugas.akhir; import java.util.list; import android.graphics.color; import android.os.bundle; import android.view.view; import android.view.view.onclicklistener; import android.widget.button; import android.widget.toast; import android.widget.togglebutton; import com.google.android.gms.maps.cameraupdate; import com.google.android.gms.maps.cameraupdatefactory; import com.google.android.gms.maps.googlemap; import com.google.android.gms.maps.googlemap.cancelablecallback; import com.google.android.gms.maps.googlemap.oninfowindowclicklistener; import com.google.android.gms.maps.supportmapfragment; import com.google.android.gms.maps.model.bitmapdescriptorfactory; import com.google.android.gms.maps.model.cameraposition; import com.google.android.gms.maps.model.latlng; import com.google.android.gms.maps.model.latlngbounds; import com.google.android.gms.maps.model.marker; import com.google.android.gms.maps.model.markeroptions; import com.google.android.gms.maps.model.polylineoptions; import com.tugas.akhir.r; import com.tugas.akhir.googlemaps.gmapv2direction; import com.tugas.akhir.googlemaps.getrotuelisttask; import com.tugas.akhir.googlemaps.gmapv2direction.direcitonreceivedlistener; import android.support.v4.app.fragmentactivity; /** * * @author omer f. kaplan * */ public class mapactivity extends fragmentactivity implements onclicklistener, oninfowindowclicklistener, direcitonreceivedlistener { private googlemap mmap; private button btndirection; latlng startposition; string startpositiontitle; string startpositionsnippet; latlng destinationposition; string destinationpositiontitle; string destinationpositionsnippet; togglebutton tbmode; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); startposition = new latlng(41.036896, 28.985490); startpositiontitle = "taksim square"; startpositionsnippet = "istanbul / turkey"; destinationposition = new latlng(41.005921, 28.977737); destinationpositiontitle = "sultanahmet mosque, istanbul"; destinationpositionsnippet = "istanbul / turkey"; btndirection = (button) findviewbyid(r.id.btndirection); btndirection.setonclicklistener(this); tbmode = (togglebutton) findviewbyid(r.id.tbmode); tbmode.setchecked(true); setupmapifneeded(); } private void setupmapifneeded() { // null check confirm have not instantiated // map. if (mmap == null) { // try obtain map supportmapfragment. mmap = ((supportmapfragment) getsupportfragmentmanager() .findfragmentbyid(r.id.map)).getmap(); // check if successful in obtaining map. if (mmap != null) { setupmap(); } } } private void setupmap() { mmap.setmaptype(googlemap.map_type_hybrid); mmap.setmylocationenabled(true); mmap.setindoorenabled(true); mmap.getuisettings().setzoomcontrolsenabled(true); mmap.getuisettings().setmylocationbuttonenabled(true); mmap.getuisettings().setcompassenabled(true); mmap.getuisettings().setallgesturesenabled(true); mmap.setoninfowindowclicklistener(this); } public void clearmap() { mmap.clear(); } @override public void onclick(view v) { if (v == btndirection) { clearmap(); markeroptions mdestination = new markeroptions() .position(destinationposition) .title(destinationpositiontitle) .snippet(destinationpositionsnippet) .icon(bitmapdescriptorfactory.fromresource(r.drawable.pin1)); markeroptions mstart = new markeroptions() .position(startposition) .title(startpositiontitle) .snippet(startpositionsnippet) .icon(bitmapdescriptorfactory.fromresource(r.drawable.pin2)); mmap.addmarker(mdestination); mmap.addmarker(mstart); if (tbmode.ischecked()) { new getrotuelisttask(mapactivity.this, startposition, destinationposition, gmapv2direction.mode_driving, this) .execute(); } else { new getrotuelisttask(mapactivity.this, startposition, destinationposition, gmapv2direction.mode_walking, this) .execute(); } } } @override public void ondirectionlistreceived(list<latlng> mpointlist) { if (mpointlist != null) { polylineoptions rectline = new polylineoptions().width(10).color( color.red); (int = 0; < mpointlist.size(); i++) { rectline.add(mpointlist.get(i)); } mmap.addpolyline(rectline); cameraposition mcpfrom = new cameraposition.builder() .target(startposition).zoom(15.5f).bearing(0).tilt(25) .build(); final cameraposition mcpto = new cameraposition.builder() .target(destinationposition).zoom(15.5f).bearing(0) .tilt(50).build(); changecamera(cameraupdatefactory.newcameraposition(mcpfrom), new cancelablecallback() { @override public void onfinish() { changecamera(cameraupdatefactory .newcameraposition(mcpto), new cancelablecallback() { @override public void onfinish() { latlngbounds bounds = new latlngbounds.builder() .include(startposition) .include( destinationposition) .build(); changecamera( cameraupdatefactory .newlatlngbounds( bounds, 50), null, false); } @override public void oncancel() { } }, false); } @override public void oncancel() { } }, true); } } /** * change camera position moving or animating camera depending on * input parameter. */ private void changecamera(cameraupdate update, cancelablecallback callback, boolean instant) { if (instant) { mmap.animatecamera(update, 1, callback); } else { mmap.animatecamera(update, 4000, callback); } } @override public void oninfowindowclick(marker selectedmarker) { if (selectedmarker.gettitle().equals(startpositiontitle)) { toast.maketext(this, "marker clicked: " + startpositiontitle, toast.length_long).show(); } else if (selectedmarker.gettitle().equals(destinationpositiontitle)) { toast.maketext(this, "marker clicked: " + destinationpositiontitle, toast.length_long).show(); } selectedmarker.hideinfowindow(); } @override protected void onresume() { super.onresume(); } }
beside mainactivity.java, write down getrotuelisttask.java, here's source code :
package com.tugas.akhir.googlemaps; import java.util.list; import android.app.progressdialog; import android.content.context; import android.net.connectivitymanager; import android.os.asynctask; import android.widget.toast; import com.google.android.gms.maps.model.latlng; import com.tugas.akhir.googlemaps.gmapv2direction.direcitonreceivedlistener; public class getrotuelisttask extends asynctask<void, void, void> { private final context mcontext; gmapv2direction mgmdirection = new gmapv2direction(); latlng fromposition; latlng toposition; list<latlng> mpointlist; private progressdialog dialog; private int mdirectionmode; direcitonreceivedlistener mlistener; public getrotuelisttask(context context, latlng fromposition, latlng toposition, int mdirectionmode, direcitonreceivedlistener mlistener) { this.mcontext = context; this.fromposition = fromposition; this.toposition = toposition; this.mdirectionmode = mdirectionmode; this.mlistener = mlistener; } @override protected void doinbackground(void... params) { mgmdirection.setparams(fromposition, toposition, mdirectionmode); mpointlist = mgmdirection.getpointlist(this.mcontext); return null; } @override protected void onpostexecute(void result) { if (dialog.isshowing()) { dialog.dismiss(); } if (mpointlist != null) { mlistener.ondirectionlistreceived(mpointlist); } else { toast.maketext(this.mcontext, "error downloading direction!", toast.length_long).show(); } } @override protected void onpreexecute() { connectivitymanager conmgr = (connectivitymanager) mcontext .getapplicationcontext().getsystemservice( context.connectivity_service); if (conmgr.getactivenetworkinfo() != null && conmgr.getactivenetworkinfo().isavailable() && conmgr.getactivenetworkinfo().isconnectedorconnecting()) { // background: connected internet dialog = new progressdialog(mcontext); dialog.setmessage("downloading directions..."); dialog.show(); } else { this.cancel(true); toast.maketext(mcontext, "not connected internet!", toast.length_long).show(); } } @override protected void oncancelled() { super.oncancelled(); } }
after according tutorial, write gmapv2direction.java :
package com.tugas.akhir.googlemaps; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.util.linkedlist; import java.util.list; import org.apache.http.httpentity; import org.apache.http.httpresponse; import org.apache.http.client.clientprotocolexception; import org.apache.http.client.httpclient; import org.apache.http.client.methods.httppost; import org.apache.http.impl.client.defaulthttpclient; import org.json.jsonarray; import org.json.jsonobject; import android.content.context; import android.util.log; import com.google.android.gms.maps.model.latlng; /** * @author kaplandroid */ public class gmapv2direction { latlng src, dest; public list<latlng> pointtodraw; public static final int mode_driving = 1; public static final int mode_walking = 2; public int mdirectionmode; public void setparams(latlng src, latlng dest, int mmode) { this.src = src; this.dest = dest; this.mdirectionmode = mmode; } public list<latlng> getpointlist(context mcontext) { if (src != null || dest != null) { // connect map web service httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost(makeurl(src, dest)); httpresponse response; try { response = httpclient.execute(httppost); httpentity entity = response.getentity(); inputstream = null; = entity.getcontent(); bufferedreader reader = new bufferedreader( new inputstreamreader(is, "iso-8859-1"), 8); stringbuilder sb = new stringbuilder(); sb.append(reader.readline() + "\n"); string line = "0"; while ((line = reader.readline()) != null) { sb.append(line + "\n"); } is.close(); reader.close(); string result = sb.tostring(); jsonobject jsonobject = new jsonobject(result); jsonarray routearray = jsonobject.getjsonarray("routes"); jsonobject routes = routearray.getjsonobject(0); jsonobject overviewpolylines = routes .getjsonobject("overview_polyline"); string encodedstring = overviewpolylines.getstring("points"); pointtodraw = decodepoly(encodedstring); } catch (clientprotocolexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } catch (exception e) { e.printstacktrace(); } return pointtodraw; } else { throw new nullpointerexception( "source or destination coordinate null. must call \"setparams(latlng,latlng)\" method first!"); } } private list<latlng> decodepoly(string poly) { int len = poly.length(); int index = 0; list<latlng> decoded = new linkedlist<latlng>(); int lat = 0; int lng = 0; while (index < len) { int b; int shift = 0; int result = 0; { b = poly.charat(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; { b = poly.charat(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; decoded.add(new latlng((lat / 1e5), (lng / 1e5))); } return decoded; } private string makeurl(latlng src, latlng dest) { stringbuilder urlstring = new stringbuilder(); urlstring.append("http://maps.googleapis.com/maps/api/directions/json"); // urlstring.append("?origin="); urlstring.append(double.tostring((double) src.latitude)); urlstring.append(","); urlstring.append(double.tostring((double) src.longitude)); // urlstring.append("&destination="); urlstring.append(double.tostring((double) dest.latitude)); urlstring.append(","); urlstring.append(double.tostring((double) dest.longitude)); urlstring.append("&sensor=false&units=metric"); if (mdirectionmode == mode_driving) { urlstring.append("&mode=driving"); } else if (mdirectionmode == mode_walking) { urlstring.append("&mode=walking"); } log.d("request url", "url=" + urlstring.tostring()); return urlstring.tostring(); } public interface direcitonreceivedlistener { public void ondirectionlistreceived(list<latlng> mpointlist); } }
then write layout :
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_alignparentleft="true" android:layout_alignparenttop="true" android:orientation="vertical" > <fragment android:id="@+id/map" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_margin="5dp" class="com.google.android.gms.maps.supportmapfragment" /> <togglebutton android:id="@+id/tbmode" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_aligntop="@+id/map" android:layout_torightof="@+id/btndirection" android:textoff="walking" android:texton="driving" /> <button android:id="@+id/btndirection" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignleft="@+id/map" android:layout_aligntop="@+id/map" android:layout_marginleft="62dp" android:text="@string/getdirection" /> </relativelayout>
finally, add code androidmanifest shown bellow :
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.tugas.akhir" android:versioncode="1" android:versionname="1.0" > <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <uses-permission android:name="android.permission.internet" /> <uses-permission android:name="android.permission.access_fine_location" /> <uses-permission android:name="android.permission.access_coarse_location" /> <uses-permission android:name="android.permission.access_network_state" /> <!-- requaired permissions google maps v2 - start - kaplandroid --> <permission android:name="com.tugas.akhir.permission.maps_receive" android:protectionlevel="signature" /> <!-- external storage caching. --> <uses-permission android:name="android.permission.write_external_storage" /> <uses-permission android:name="com.google.android.providers.gsf.permission.read_gservices" /> <uses-permission android:name="com.tugas.akhir.permission.maps_receive" /> <!-- maps api needs opengl es 2.0. --> <uses-feature android:glesversion="0x00020000" android:required="true" /> <!-- requaired permissions google maps v2 - end - kaplandroid --> <application android:allowbackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/apptheme" > <!-- api key google maps v2 - start - kaplandroid --> <meta-data android:name="com.google.android.maps.v2.api_key" android:value="-------- google api key -------------" /> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <!-- api key google maps v2 - end - kaplandroid --> <activity android:name="com.tugas.akhir.mapactivity" android:label="@string/app_name" android:screenorientation="portrait" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> </application> <uses-permission android:name="android.permission.internet" /> </manifest>
later export .apk file, install device. but,... when open it, didnt show maps, show plus & minus button, there nothing except button. i've search internet, said problem put code androidmanifest :
<uses-permission android:name="android.permission.internet" />
i've put code, still doesnt show maps, article said problem reference google play library. i've successfull reference project google-play-service library, it's still failed. can fix problem, please ??? thank much
it looks sha1 hash of certificates or packageid use incorrectly set in google api console maps. it's important use proper sha1 hash , right package id. note may want add debug certificate well.
Comments
Post a Comment