0

I have a map where i display some markers that are stored in a db (MySQL), for each marker there are some other fields that goes with it (for example name,adress, category, etc.)what i want to do is compare if the field "category" is equals "category A" change the icon of the marker, how can i make this possible? Any idea is appreciated!

I was trying something like this, but it didn't work out:

 if(location.get(i).get("campo_categoria").toString()=="Obras publicas")
        //if (name=="Obras publicas")
        {
            new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op));

Main:

ArrayList<HashMap<String, String>> location = null;
    String url = "http://appserver.puertovallarta.gob.mx/movil/getLanLong2.php";
    try {

        JSONArray data = new JSONArray(getHttpGet(url));
        location = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        for(int i = 0; i < data.length(); i++){
            JSONObject c = data.getJSONObject(i);
            map = new HashMap<String, String>();
            map.put("id", c.getString("id"));
            map.put("campo_latitud", c.getString("campo_latitud"));
            map.put("campo_longitud", c.getString("campo_longitud"));
            map.put("campo_categoria", c.getString("campo_categoria"));
            location.add(map);
        }
    } catch (JSONException e) {
// TODO Auto-generated catch block
        e.printStackTrace();
    }

    String campouno = "";
    if(!TextUtils.isEmpty(campouno)){
        double campo_latitud = Double.parseDouble(campouno);
    }
    //campo_latitud = Double.parseDouble(location.get(0).get("Latitude").toString());
    String campodos = "";
    if(!TextUtils.isEmpty(campodos)){
        double campo_longitud = Double.parseDouble(campodos);
    }

    for (int i = 0; i < location.size(); i++) {
        if(!TextUtils.isEmpty(location.get(i).get("campo_latitud").toString())&&!TextUtils.isEmpty(location.get(i).get("campo_longitud").toString())) {
            campo_latitud = Double.parseDouble(location.get(i).get("campo_latitud").toString());
            campo_longitud = Double.parseDouble(location.get(i).get("campo_longitud").toString());
        }

    String name = location.get(i).get("campo_categoria").toString();

        LatLng downtown = new LatLng(20.663203, -105.228053);
        googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(campo_latitud, campo_longitud))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
            .title(name));

        if(location.get(i).get("campo_categoria").toString()=="Obras publicas")
        //if (name=="Obras publicas")
        {
            new MarkerOptions().icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op));
        }

        googleMap.moveCamera(CameraUpdateFactory.newLatLng(downtown));
    googleMap.setLatLngBoundsForCameraTarget(ADELAIDE);
}}

PHP file:

<?php
require_once 'dbDetails.php';
$sql = "SELECT * FROM `reportes2` ORDER BY id ASC";
$objQuery = mysqli_query($con,$sql);

$arrRows = array();
$arryItem = array();

while($arr = mysqli_fetch_array($objQuery)) {

$arryItem["id"] = $arr["id"];
$arryItem["campo_latitud"] = $arr["campo_latitud"];
$arryItem["campo_longitud"] = $arr["campo_longitud"];
$arryItem["campo_categoria"] = $arr["campo_categoria"];
$arryItem["campo_descripcion"] = $arr["campo_descripcion"];

$arrRows[] = $arryItem;

}
General Grievance
  • 4,555
  • 31
  • 31
  • 45
Armando
  • 47
  • 10
  • 1
    you can add $sql = "SELECT * FROM `reportes2` WHERE YourNo=1 ORDER BY id ASC";`. – Lalit Fauzdar Oct 19 '17 at 06:56
  • Thanks @LalitSinghFauzdar , that worked smoothly, you help me out a lot! – Armando Oct 19 '17 at 07:13
  • No problem Mate. – Lalit Fauzdar Oct 19 '17 at 07:13
  • Bro @LalitSinghFauzdar , i have a question i want to say that "else if(location.get(i).get("campo_categoria").toString().equals("Obras publicas")&&(location.get(i).get("campo_estado").toString().equals("En proceso"))){ googleMap.addMarker(new MarkerOptions().position(new LatLng(campo_latitud, campo_longitud)).title(name).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_pa)));" but don't see a marker, is this correct? – Armando Oct 20 '17 at 01:53
  • Try placing a Toast or Log D in that if to check whether it's reachable or not. – Lalit Fauzdar Oct 20 '17 at 03:30
  • I already added it as you said but can't see any toast showing up @LalitSinghFauzdar – Armando Oct 20 '17 at 04:17
  • this simply means it has no condition as the condition you're using. But as you've placed an extra pair of parenthesis in the code commented above, try this code without that extra pair of parenthesis `else if( location.get(i).get("campo_categoria").toString().equals(‌"Obras publicas") && location.get(i).get("campo_estado").toString().‌​equals("En proceso") ){ googleMap.addMarker(new MarkerOptions().position(new LatLng(campo_latitud, campo_longitud)).title(name).icon(BitmapDescriptorFactory.fr‌​omResource(R.drawabl‌​e.ic_pa))); }`. Extra pair of parenthesis could be the reason. – Lalit Fauzdar Oct 20 '17 at 05:49
  • Neither like that, without the parenthesis @LalitSinghFauzdar :/ – Armando Oct 20 '17 at 06:35
  • So it's database's fault. Either You don't have such marker or any typo is stopping your code to work. – Lalit Fauzdar Oct 20 '17 at 06:43
  • The marker exists, i mean i created it to test this part, mate i want to use a costum infowindow but not sure how to implement it, can you give me a hand? https://stackoverflow.com/questions/46841301/use-custom-infowindow-with-mysql – Armando Oct 20 '17 at 06:49
  • 1
    By the way i solved the condition matter by writting this: "if(location.get(i).get("campo_estado").toString().equals("En proceso")&&location.get(i).get("campo_categoria").toString().equals("Ecolog?a")){googleMap.addMarker...(R.drawable.ic_eco_yellow)));}elseif(location.get(i).get("campo_estado").toString().equals("Pendiente")&&location.get(i).get("campo_categoria").toString().equals("Ecolog?a")){googleMap.addMarker...(R.drawable.ic_eco_red)));}" – Armando Oct 20 '17 at 07:13
  • Good to go mate – Lalit Fauzdar Oct 20 '17 at 07:23

2 Answers2

1

try this Approach.!

String BLUE_COLOR="blue";
String RED_COLOR="red";

      String campoCategoria= location.get(i).get("campo_categoria").toString(); 
            googleMap.addMarker(new MarkerOptions()
                .position(new LatLng(campo_latitud, campo_longitud))
                .icon(BitmapDescriptorFactory.fromResource(getIconUsingSwitch(campoCategoria)))
                .title(name));


 private int void getIconUsingSwitch(String campoCategoria) {
            switch (campoCategoria) {
            case "blue":
                return R.drawable.ic_blue;
                break;
            case "red":
                return R.drawable.ic_red;
                break;
            default:
                return R.drawable.ic_normal;
            }
        }

for String use equalsIgnoreCase and for Object use equals

this will ignore Upper case and lower case BLUE or blue it will run for both

  void getIconUsingIf(String campoCategoria) {

    if (campoCategoria.equalsIgnoreCase(BLUE_COLOR)) {
        return R.drawable.ic_blue;
    } else if (campoCategoria.equalsIgnoreCase(RED_COLOR)) {
        return R.drawable.ic_red;
    } else {
        return R.drawable.ic_normal;
    }

}
Atif AbbAsi
  • 5,633
  • 7
  • 26
  • 47
  • Are there any disadventages when using if? i can also give it a try to this method you posted – Armando Oct 19 '17 at 05:45
  • Welcome @Armando try to make your programming skills clean..use best approaches(Professional Approaches) rather then using unprofessional Approaches.if you keep on using improper way of programming you may become coder but not a good and efficient programmer.! – Atif AbbAsi Oct 19 '17 at 05:46
  • @Armando you are using For loop in your method and then adding if will make it more slower. and never use compare if == this I will never recommend this thing.! its unprofessional way.! – Atif AbbAsi Oct 19 '17 at 05:54
  • 1
    That's why I said use Objects.equals. Using == for strings is improper, see [here](https://stackoverflow.com/questions/7520432/what-is-the-difference-between-vs-equals-in-java). – Lalit Fauzdar Oct 19 '17 at 06:06
  • @AtifAbbAsi The moment you posted this answer, it was a pretty clean way but now not. Why? Because Using a method call + If inside this method is obviously slower than only if-else. And Unless you are making a million calls, it doesn't even matter. Also, to point something out, Why will he bother using a function call + if. And I think you didn't read, I'm using 17 if-elseif-else in a for-loop which actually places all my markers(165) and polylines(8 polylines between all these markers) and I can't spot a single second delay in any device. – Lalit Fauzdar Oct 19 '17 at 06:16
  • Switch and If both are same but if you are using 17 if else then its not a good approach I recommend you to use switch instead of if. Code should be clean and easy to understand remember.try to read about clean architecture.! @LalitSinghFauzdar – Atif AbbAsi Oct 19 '17 at 07:43
  • I know that very well but But the Frontend is what user cares about. The backend is on the developer and I've created a separate method for all my polylines and Markers and it works/looks great. It's about how you use features of programming, If if is wrong, it wouldn't have created. And My code is pretty clean I can assure you that. – Lalit Fauzdar Oct 19 '17 at 07:51
  • user do care about backend maybe you have never meet any real client. and look at your code size & mine..you are using approach of a coder not a programmer..! @LalitSinghFauzdar – Atif AbbAsi Oct 19 '17 at 07:55
  • Bro, You're not stopping. Why? It's not fixed or necessary that you can't create a better-looking backend of an app with If. I have a pretty looking brilliantly working very (very very) large project with more than 70k entries in the database covering more than 8 cities and you really care about switch or if. Don't bother. It looks good. It's just an unstoppable debate. – Lalit Fauzdar Oct 19 '17 at 07:59
  • I've done various things people don't do to make my code look code like ordering methods in size or whatever just to make it more and more understandable. That's why I'm saying it looks good. This is just an answer on SO. You can't relate it to my project or my programming skills or my coding nature. – Lalit Fauzdar Oct 19 '17 at 08:01
-1

Try this:

  LatLng downtown = new LatLng(20.663203, -105.228053);
  for (int i = 0; i < location.size(); i++) {
            if(!TextUtils.isEmpty(location.get(i).get("campo_latitud").toString())&&!TextUtils.isEmpty(location.get(i).get("campo_longitud").toString())) {
                campo_latitud = Double.parseDouble(location.get(i).get("campo_latitud").toString());
                campo_longitud = Double.parseDouble(location.get(i).get("campo_longitud").toString());
            }
            String name = location.get(i).get("campo_categoria").toString();    
            if (Objects.equals(location.get(i).get("campo_categoria").toString(),"Obras publicas")) {
                googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(campo_latitud, campo_longitud))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op1))
            .title(name));

            } else if (Objects.equals(location.get(i).get("campo_categoria").toString(),"Any other Choice")) {
                googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(campo_latitud, campo_longitud))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op2))
            .title(name));
            } 
            else {
                 googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(campo_latitud, campo_longitud))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.marker))
            .title(name));
            }
        }
        googleMap.moveCamera(CameraUpdateFactory.newLatLng(downtown));
        googleMap.setLatLngBoundsForCameraTarget(ADELAIDE);

This way you'll have different markers for different categories and you can use many else-if without any problem. I've 17 in mine and works great.

ALso, to manage all these markers you can create a List as List<Marker> list = new ArrayList<>(); and then can add markers in it as

Marker marker = googleMap.addMarker(new MarkerOptions()
            .position(new LatLng(campo_latitud, campo_longitud))
            .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op1))
            .title(name));
list.add(marker);

You can then access any marker from it as:

   Marker m = list.get(5); //position of needed marker
   m.getTitle or m.getPosition or m.getAlpha //all these will then work

You can also use for loops as well:

for(Marker m:list){
if (m.getTitle().equals("Your Title")) {
            m.showInfoWindow();
            CameraPosition cameraPosition = new CameraPosition.Builder().target(m.getPosition()).zoom(14).build();
            googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
            break;
        }

The above for loop code is directly copied from my project which actually highlights the selected marker from a spinner in my map activity between 150+ markers.

Something I've missed, tell me I can help.

Lalit Fauzdar
  • 5,953
  • 2
  • 26
  • 50
  • 1
    Thanks, i just added the "String name = location.get(i).get("campo_categoria").toString(); if (location.get(i).get("campo_categoria").toString()=="Obras publicas")) { googleMap.addMarker(new MarkerOptions() .position(new LatLng(campo_latitud, campo_longitud)) .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op1)) .title(name));" part, but when running the app im not able to see any marker, i dont know why – Armando Oct 19 '17 at 04:35
  • @Armando Why are you double checking it? Just use `if (Objects.equals(name,"Obras publicas")`. – Lalit Fauzdar Oct 19 '17 at 05:06
  • Addition to it, Objects.euqals should be used with strings as == checks for item type. – Lalit Fauzdar Oct 19 '17 at 05:07
  • Thanks so much,it is working now, i just change the == to .equals, i have another question, can i post it and let you know? – Armando Oct 19 '17 at 05:32
  • Well, what i want to do now is on the data base there's stored a number (1 and 0) in a field (for example accepted "1") so if the number is 0 then don't show this marker if it is 1 show it, i don't know if im clear enough? – Armando Oct 19 '17 at 06:27
  • You can simply add a where clause to your cursor's query like this. `String query = "select name, Lat, Long from YOurTableName where yourNo = 1;";` – Lalit Fauzdar Oct 19 '17 at 06:41
  • @Armando Just add a where clause to it and this way it only selects the markers which have value = 1. Using this way will save you from extending the if-else. But if you want to extend if, you can just use `if (Objects.equals(location.get(i).get("campo_categoria").toString(),"Obras publicas") && yourno == 1 ){ your code}`. – Lalit Fauzdar Oct 19 '17 at 06:45
  • See, Objects.equals for String and == for Int. – Lalit Fauzdar Oct 19 '17 at 06:46
  • I already updated the php file, and clear about the objetcs.equals for Strings and == for int, thanks for the information – Armando Oct 19 '17 at 06:53