0
votes

I'm trying to show the name of the place in marker. I'm applying someone's code and want to change the price to the name.

I tried to change some lines, but the results aren't what I intented.

  1. MarkerFromLatLong2.java

     public class MarkerFromLatLong2 extends FragmentActivity implements   OnMapReadyCallback, GoogleMap.OnMarkerClickListener, GoogleMap.OnMapClickListener {
    
    
    String myJSON;
    public static final String TAG_RESULTS = "result";
    public static final String TAG_LAT = "lat";
    public static final String TAG_LON = "lon";
    String lat;
    String lon;
    String price;
    char a, b, c, d, e;
    
    JSONArray reservedtimes = null;
    
    ArrayList<HashMap<String, String>> latlonList;
    
    Marker selectedMarker;
    View marker_root_view;
    TextView tv_marker;
    public GoogleMap mMap;
    final Context context = this;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    
        lat = new String();
        lon = new String();
        myJSON = new String();
        latlonList = new ArrayList<HashMap<String, String>>();
        getData("http://MY ADDRESS/getdata.php");
    }
    
    public void getData(String url) {
        class GetDataJSON extends AsyncTask<String, Void, String> {
    
            @Override
            public String doInBackground(String... params) {
    
                String uri = params[0];
    
                BufferedReader bufferedReader = null;
                try {
                    URL url = new URL(uri);
                    HttpURLConnection con = (HttpURLConnection) url.openConnection();
                    StringBuilder sb = new StringBuilder();
    
                    bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    
                    String json;
                    while ((json = bufferedReader.readLine()) != null) {
                        sb.append(json + "\n");
                    }
    
                    return sb.toString().trim();
    
                } catch (Exception e) {
                    return null;
                }
            }
    
            @Override
            public void onPostExecute(String result) {
                myJSON = result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute(url);
    }
    
    
    public void showList() {
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            reservedtimes = jsonObj.getJSONArray(TAG_RESULTS);
    
            for (int i = 0; i < reservedtimes.length(); i++) {
                JSONObject c = reservedtimes.getJSONObject(i);
                lat = c.getString(TAG_LAT);
                lon = c.getString(TAG_LON);
    
                HashMap<String, String> location = new HashMap<>();
    
                location.put(TAG_LAT, lat);
                location.put(TAG_LON, lon);
    
                latlonList.add(location);
    
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }//여기까지
    
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
    
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.546167, 126.964673), 16));
        mMap.setOnMarkerClickListener(this);
        mMap.setOnMapClickListener(this);
    
        setCustomMarkerView();
        getSampleMarkerItems();
    }
    
    
    public void setCustomMarkerView() {
        marker_root_view = LayoutInflater.from(this).inflate(R.layout.marker_layout, null);
        tv_marker = (TextView) marker_root_view.findViewById(R.id.tv_marker);
    }
    
    public void getSampleMarkerItems() {
        ArrayList<MarkerItem> sampleList = new ArrayList();
    
        /*sampleList.add(new MarkerItem(Double.valueOf(lat), Double.valueOf(lon), 1906));
    
        sampleList.add(new MarkerItem(37.546167, 126.96568, 1906));
        sampleList.add(new MarkerItem(37.538523, 126.96568, 2500000));
        sampleList.add(new MarkerItem(37.527523, 126.96568, 100000));
        sampleList.add(new MarkerItem(37.549523, 126.96568, 15000));
        sampleList.add(new MarkerItem(37.538523, 126.95768, 5000));*/
    
        Intent intent = getIntent();
    
        Double latitude = intent.getDoubleExtra("lat", 000.000000D);
        Double longitude = intent.getDoubleExtra("lon", 000.000000D);
        Character price = intent.getCharExtra("price", (char) 123);
    
        sampleList.add(new MarkerItem(latitude, longitude, price));
    
        //sampleList.add(new MarkerItem(37.546167, 126.964673, 1906));
        sampleList.add(new MarkerItem(37.538523, 126.96568, b));
        sampleList.add(new MarkerItem(37.527523, 126.96568, c));
        sampleList.add(new MarkerItem(37.549523, 126.96568, d));
        sampleList.add(new MarkerItem(37.538523, 126.95768, e));
    
        for (MarkerItem markerItem : sampleList) {
            addMarker(markerItem, false);
        }
    }
    //get the lat and lon in order
    //
    
    
    public Marker addMarker(MarkerItem markerItem, boolean isSelectedMarker) {
    
        LatLng position = new LatLng(markerItem.getLat(), markerItem.getLon());
    
        char price = markerItem.getPrice();
        //String formatted = NumberFormat.getInstance().format((price)); //only shows 0(zero)
        //String formatted = String.format(String.valueOf(price)); //shows nothing(blank) in marker
        String formatted = NumberFormat.getInstance().format((price)); //only shows 0(zero)
    
        tv_marker.setText(formatted);
    
        if (isSelectedMarker) {
            tv_marker.setBackgroundResource(R.drawable.ic_marker_phone_blue);
            tv_marker.setTextColor(Color.WHITE);
        } else {
            tv_marker.setBackgroundResource(R.drawable.ic_marker_phone);
            tv_marker.setTextColor(Color.BLACK);
        }
    
        MarkerOptions markerOptions = new MarkerOptions();
        //markerOptions.title(Integer.toString(price)); // If I delete or change the code, the app stops after I click the marker.
        markerOptions.title(Integer.toString(price)); // If I delete or change the code, the app stops after I click the marker.
        markerOptions.position(position);
        markerOptions.icon(BitmapDescriptorFactory.fromBitmap(createDrawableFromView(this, marker_root_view)));
    
        return mMap.addMarker(markerOptions);
    
    }
    
    
    // change the View to Bitmap
    public Bitmap createDrawableFromView(Context context, View view) {
    
        DisplayMetrics displayMetrics = new DisplayMetrics();
        ((Activity) context).getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        view.measure(displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.layout(0, 0, displayMetrics.widthPixels, displayMetrics.heightPixels);
        view.buildDrawingCache();
        Bitmap bitmap = Bitmap.createBitmap(view.getMeasuredWidth(), view.getMeasuredHeight(), Bitmap.Config.ARGB_8888);
    
        Canvas canvas = new Canvas(bitmap);
        view.draw(canvas);
    
        return bitmap;
    }
    
    public Marker addMarker(Marker marker, boolean isSelectedMarker) {
        double lat = marker.getPosition().latitude;
        double lon = marker.getPosition().longitude;
        char price = (char) Integer.parseInt(marker.getTitle());
        MarkerItem temp = new MarkerItem(lat, lon, price);
        return addMarker(temp, isSelectedMarker);
    
    }
    
    @Override
    public boolean onMarkerClick(Marker marker) { //If I click a marker, move my center position to equal the marker's position.
    
        CameraUpdate center = CameraUpdateFactory.newLatLng(marker.getPosition());
        mMap.animateCamera(center);
    
        changeSelectedMarker(marker);
    
        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
        alertDialogBuilder.setTitle("SP #1")
                .setMessage("Want to reserve?\n")
                .setCancelable(false)
                .setPositiveButton("Reserve",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //Moving to the reservation screen
                                Intent intent = new Intent(MarkerFromLatLong2.this, ReserveActivity.class);
                                startActivity(intent);
                            }
                        })
                .setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //cancel the dialog
                                dialog.cancel();
                            }
                        });
        //make a dialog
        AlertDialog alertDialog = alertDialogBuilder.create();
        alertDialog.show();
        return true;
    }
    
    public void changeSelectedMarker(Marker marker) {
        // return the marker which was selected by user
        if (selectedMarker != null) {
            addMarker(selectedMarker, false);
            selectedMarker.remove();
        }
    
        // point the marker selected
        if (marker != null) {
            selectedMarker = addMarker(marker, true);
            marker.remove();
        }
    }
    
    @Override
    public void onMapClick(LatLng latLng) {
        changeSelectedMarker(null);
    }
    } //If user clicks the map where the marker doesn't exist, the map turns back to the starting status.
    
  2. MarkerItem.java

    public class MarkerItem {
     double lat;
    double lon;
    char price;
    
    public MarkerItem(double lat, double lon, char price) {
        this.lat = lat;
        this.lon = lon;
        this.price = price;
    }
    
    public double getLat() {
        return lat;
    }
    
    public void setLat(double lat) {
        this.lat = lat;
    }
    
    public double getLon() {
        return lon;
    }
    
    public void setLon(double lon) {
        this.lon = lon;
    }
    
    public char getPrice() {
        return price;
    }
    
    public void setPrice(char price) {
        this.price = price;
    }
    
    
     }
    

And this is the logcat when I edited the line markerOptions.title(Integer.toString(price)); to markerOptions.title("KFC"); .

I/dalvikvm: Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method com.google.android.gms.common.zze.zzs W/dalvikvm: VFY: unable to resolve virtual method 598: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller; D/dalvikvm: VFY: replacing opcode 0x6e at 0x001b I/zzai: Making Creator dynamically D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS W/dalvikvm: VFY: unable to resolve static field 784 (SUPPORTED_64_BIT_ABIS) in Landroid/os/Build; D/dalvikvm: VFY: replacing opcode 0x62 at 0x0008 D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_ABIS W/dalvikvm: VFY: unable to resolve static field 785 (SUPPORTED_ABIS) in Landroid/os/Build; D/dalvikvm: VFY: replacing opcode 0x62 at 0x0008 D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS W/dalvikvm: VFY: unable to resolve static field 784 (SUPPORTED_64_BIT_ABIS) in Landroid/os/Build; D/dalvikvm: VFY: replacing opcode 0x62 at 0x0012 D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_32_BIT_ABIS W/dalvikvm: VFY: unable to resolve static field 783 (SUPPORTED_32_BIT_ABIS) in Landroid/os/Build; D/dalvikvm: VFY: replacing opcode 0x62 at 0x0021 D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS I/dalvikvm: DexOpt: unable to optimize static field ref 0x0310 at 0x0d in Lcom/google/android/chimera/container/internal/NativeLibUtils;.a D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_64_BIT_ABIS I/dalvikvm: DexOpt: unable to optimize static field ref 0x0310 at 0x17 in Lcom/google/android/chimera/container/internal/NativeLibUtils;.getSupportedAbisForCurrentRuntime D/dalvikvm: DexOpt: couldn't find static field Landroid/os/Build;.SUPPORTED_32_BIT_ABIS I/dalvikvm: DexOpt: unable to optimize static field ref 0x030f at 0x26 in Lcom/google/android/chimera/container/internal/NativeLibUtils;.getSupportedAbisForCurrentRuntime I/PersonaManager: getPersonaService() name persona_policy I/dalvikvm: Could not find method android.content.ContextWrapper.createCredentialProtectedStorageContext, referenced from method com.google.android.chimera.ModuleContext.createCredentialProtectedStorageContext W/dalvikvm: VFY: unable to resolve virtual method 2232: Landroid/content/ContextWrapper;.createCredentialProtectedStorageContext ()Landroid/content/Context; D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002 I/dalvikvm: Could not find method android.content.ContextWrapper.createDeviceProtectedStorageContext, referenced from method com.google.android.chimera.ModuleContext.createDeviceProtectedStorageContext W/dalvikvm: VFY: unable to resolve virtual method 2233: Landroid/content/ContextWrapper;.createDeviceProtectedStorageContext ()Landroid/content/Context; D/dalvikvm: VFY: replacing opcode 0x6f at 0x0002 W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation I/Google Maps Android API: Google Play services client version: 9877000 I/Google Maps Android API: Google Play services package version: 10084030 I/dalvikvm: Could not find method android.content.pm.PackageManager.getPackageInstaller, referenced from method kx.a W/dalvikvm: VFY: unable to resolve virtual method 2017: Landroid/content/pm/PackageManager;.getPackageInstaller ()Landroid/content/pm/PackageInstaller; D/dalvikvm: VFY: replacing opcode 0x6e at 0x001c W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskWriteViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation E/dalvikvm: Could not find class 'com.google.android.chimera.Activity', referenced from method lq.b W/dalvikvm: VFY: unable to resolve instanceof 600 (Lcom/google/android/chimera/Activity;) in Llq; D/dalvikvm: VFY: replacing opcode 0x20 at 0x016f W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation I/c: Token loaded from file. Expires in: 354701377 ms. I/c: Scheduling next attempt in 354401 seconds. D/AbsListView: Get MotionRecognitionManager W/f: Suppressed StrictMode policy violation: StrictModeDiskWriteViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskWriteViolation W/ContextImpl: Failed to ensure directory: /storage/extSdCard/Android/data/com.example.jina.a1105gmdemo/cache W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskWriteViolation W/f: Suppressed StrictMode policy violation: StrictModeDiskReadViolation I/Choreographer: Skipped 152 frames! The application may be doing too much work on its main thread. I/dalvikvm: Could not find method android.os.PowerManager.isInteractive, referenced from method maps.y.t.a W/dalvikvm: VFY: unable to resolve virtual method 2324: Landroid/os/PowerManager;.isInteractive ()Z D/dalvikvm: VFY: replacing opcode 0x6e at 0x0047 W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found. I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2 I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2 E/DynamiteModule: Failed to load DynamiteLoader: java.lang.ClassNotFoundException: Didn't find class "com.google.android.gms.dynamite.DynamiteModule$DynamiteLoaderClassLoader" on path: DexPathList[[zip file "/data/app/com.example.jina.a1105gmdemo-144.apk", zip file "/data/data/com.example.jina.a1105gmdemo/code_cache/secondary-dexes/com.example.jina.a1105gmdemo-144.apk.classes2.zip"],nativeLibraryDirectories=[/data/app-lib/com.example.jina.a1105gmdemo-144, /vendor/lib, /system/lib]] W/DynamiteModule: Failed to load remote module: Failed to get module context W/DynamiteModule: Failed to load module via fast routeub: Remote load failed. No local fallback found. W/DynamiteModule: Local module descriptor class for com.google.android.gms.googlecertificates not found. I/DynamiteModule: Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:2 I/DynamiteModule: Selected remote version of com.google.android.gms.googlecertificates, version >= 2

2

2 Answers

0
votes

I think this going to be useful for you link. You can simply implement interface Google.InfoWindowAdapter, which have method called getInfoContents(Marker marker). In this method inflate layout in which you gonna put info about selected marker.

I used this in many projects.

P.S Sorry for bad English

0
votes
  markerOptions.title(Integer.toString(price)); `

Edit this line and pass name as argument ,

For example

markerOptions.title("KFC");