@Override
  public void setStartMarker(MapPos startPos) {
    routeLayer.clear();
    markerLayer.clear();

    markerLayer.add(startMarker);
    startMarker.setMapPos(startPos);
    startMarker.setVisible(true);
  }
  @Override
  public void routeResult(Route route) {

    if (route.getRouteResult() != Route.ROUTE_RESULT_OK) {
      Toast.makeText(this, "Route error", Toast.LENGTH_LONG).show();
      return;
    }

    routeLayer.clear();
    routeLayer.add(route.getRouteLine());
    Log.debug("route line points: " + route.getRouteLine().getVertexList().size());
    //        Log.debug("route line: "+route.getRouteLine().toString());
    markerLayer.addAll(
        CloudMadeDirections.getRoutePointMarkers(
            routeImages, MARKER_SIZE, route.getInstructions()));
    mapView.requestRender();
    Toast.makeText(this, "Route " + route.getRouteSummary(), Toast.LENGTH_LONG).show();
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

    Log.enableAll();
    Log.setTag("cloudmade");

    // 1. Get the MapView from the Layout xml - mandatory
    mapView = (MapView) findViewById(R.id.mapView);

    // Optional, but very useful: restore map state during device rotation,
    // it is saved in onRetainNonConfigurationInstance() below
    Components retainObject = (Components) getLastNonConfigurationInstance();
    if (retainObject != null) {
      // just restore configuration, skip other initializations
      mapView.setComponents(retainObject);
      // add event listener
      RouteMapEventListener mapListener = new RouteMapEventListener(this);
      mapView.getOptions().setMapListener(mapListener);

      mapView.startMapping();
      return;
    } else {
      // 2. create and set MapView components - mandatory
      Components components = new Components();
      mapView.setComponents(components);
      // add event listener
      RouteMapEventListener mapListener = new RouteMapEventListener(this);
      mapView.getOptions().setMapListener(mapListener);
    }

    // use special style for high-density devices
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    String cloudMadeStyle = "997";

    if (metrics.densityDpi >= DisplayMetrics.DENSITY_HIGH) {
      cloudMadeStyle = "997@2x";
    }

    TMSMapLayer mapLayer =
        new TMSMapLayer(
            new EPSG3857(),
            0,
            18,
            0,
            "http://b.tile.cloudmade.com/" + CLOUDMADE_KEY + "/" + cloudMadeStyle + "/256/",
            "/",
            ".png");
    mapView.getLayers().setBaseLayer(mapLayer);

    // Location: London
    mapView.setFocusPoint(
        mapView.getLayers().getBaseLayer().getProjection().fromWgs84(-0.1f, 51.51f));
    mapView.setZoom(14.0f);

    // routing layers
    routeLayer = new GeometryLayer(new EPSG3857());
    mapView.getLayers().addLayer(routeLayer);

    // create markers for start & end, and a layer for them
    Bitmap olMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.olmarker);
    StyleSet<MarkerStyle> startMarkerStyleSet =
        new StyleSet<MarkerStyle>(
            MarkerStyle.builder()
                .setBitmap(olMarker)
                .setColor(Color.GREEN)
                .setSize(MARKER_SIZE)
                .build());
    startMarker =
        new Marker(new MapPos(0, 0), new DefaultLabel("Start"), startMarkerStyleSet, null);

    StyleSet<MarkerStyle> stopMarkerStyleSet =
        new StyleSet<MarkerStyle>(
            MarkerStyle.builder()
                .setBitmap(olMarker)
                .setColor(Color.RED)
                .setSize(MARKER_SIZE)
                .build());
    stopMarker = new Marker(new MapPos(0, 0), new DefaultLabel("Stop"), stopMarkerStyleSet, null);

    markerLayer = new MarkerLayer(new EPSG3857());
    mapView.getLayers().addLayer(markerLayer);

    // make markers invisible until we need them
    //        startMarker.setVisible(false);
    //        stopMarker.setVisible(false);
    //
    markerLayer.add(startMarker);
    markerLayer.add(stopMarker);

    // define images for turns
    // source: http://mapicons.nicolasmollet.com/markers/transportation/directions/directions/
    // TODO: use better structure than plain array for this
    routeImages[CloudMadeDirections.IMAGE_ROUTE_START] =
        UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_up);
    routeImages[CloudMadeDirections.IMAGE_ROUTE_RIGHT] =
        UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_upthenright);
    routeImages[CloudMadeDirections.IMAGE_ROUTE_LEFT] =
        UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_upthenleft);
    routeImages[CloudMadeDirections.IMAGE_ROUTE_STRAIGHT] =
        UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_up);
    routeImages[CloudMadeDirections.IMAGE_ROUTE_END] =
        UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.direction_down);

    // rotation - 0 = north-up
    mapView.setRotation(0f);
    // tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed
    // is 30 degrees.
    mapView.setTilt(90.0f);

    // Activate some mapview options to make it smoother - optional
    mapView.getOptions().setPreloading(true);
    mapView.getOptions().setSeamlessHorizontalPan(true);
    mapView.getOptions().setTileFading(true);
    mapView.getOptions().setKineticPanning(true);
    mapView.getOptions().setDoubleClickZoomIn(true);
    mapView.getOptions().setDualClickZoomOut(true);

    // set sky bitmap - optional, default - white
    mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
    mapView.getOptions().setSkyOffset(4.86f);
    mapView
        .getOptions()
        .setSkyBitmap(UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.sky_small));

    // Map background, visible if no map tiles loaded - optional, default - white
    mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
    mapView
        .getOptions()
        .setBackgroundPlaneBitmap(
            UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.background_plane));
    mapView.getOptions().setClearColor(Color.WHITE);

    // configure texture caching - optional, suggested
    mapView.getOptions().setTextureMemoryCacheSize(20 * 1024 * 1024);
    mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);

    // define online map persistent caching - optional, suggested. Default - no caching
    mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath());
    // set persistent raster cache limit to 100MB
    mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);

    // 4. zoom buttons using Android widgets - optional
    // get the zoomcontrols that was defined in main.xml
    ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoomcontrols);
    // set zoomcontrols listeners to enable zooming
    zoomControls.setOnZoomInClickListener(
        new View.OnClickListener() {
          public void onClick(final View v) {
            mapView.zoomIn();
          }
        });
    zoomControls.setOnZoomOutClickListener(
        new View.OnClickListener() {
          public void onClick(final View v) {
            mapView.zoomOut();
          }
        });

    Toast.makeText(
            getApplicationContext(), "Click on map to set route start and end", Toast.LENGTH_SHORT)
        .show();
  }
 @Override
 public void setStopMarker(MapPos pos) {
   markerLayer.add(stopMarker);
   stopMarker.setMapPos(pos);
   stopMarker.setVisible(true);
 }
  @SuppressLint("NewApi")
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow()
        .setFlags(
            WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    setContentView(R.layout.activity_pieturas);

    // enable logging for troubleshooting - optional
    Log.enableAll();
    Log.setTag("rigassatiksme");

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
      KarteActivity.marsruta_nr = extras.getString("marsruta_nr");
      KarteActivity.transporta_tips = extras.getString("transporta_tips");
      KarteActivity.virziens = extras.getString("virziens");
      KarteActivity.pieturas_nosaukums = extras.getString("pieturas_nosaukums");

      setTitle("karte: " + PieturaActivity.pieturas_nosaukums);
    }

    // 1. Get the MapView from the Layout xml - mandatory
    mapView = (MapView) findViewById(R.id.mapView);

    // Optional, but very useful: restore map state during device rotation,
    // it is saved in onRetainNonConfigurationInstance() below
    Components retainObject = (Components) getLastNonConfigurationInstance();
    if (retainObject != null) {
      // just restore configuration and update listener, skip other initializations
      mapView.setComponents(retainObject);
      MapEventListener mapListener = (MapEventListener) mapView.getOptions().getMapListener();
      mapListener.reset(this, mapView);
      mapView.startMapping();
      return;
    } else {
      // 2. create and set MapView components - mandatory
      mapView.setComponents(new Components());
    }

    // 3. Define map layer for basemap - mandatory.
    // Here we use MapQuest open tiles
    // Almost all online tiled maps use EPSG3857 projection.
    TMSMapLayer mapLayer =
        new TMSMapLayer(
            new EPSG3857(), 0, 18, 0, "http://otile1.mqcdn.com/tiles/1.0.0/osm/", "/", ".png");

    mapView.getLayers().setBaseLayer(mapLayer);

    // set initial map view camera - optional. "World view" is default
    // Location: Pïavnieki
    // NB! it must be in base layer projection (EPSG3857), so we convert it from lat and long
    mapView.setFocusPoint(
        mapView.getLayers().getBaseLayer().getProjection().fromWgs84(24.1132, 56.9514));

    // rotation - 0 = north-up
    mapView.setRotation(0f);
    // zoom - 0 = world, like on most web maps
    mapView.setZoom(11.0f);
    // tilt means perspective view. Default is 90 degrees for "normal" 2D map view, minimum allowed
    // is 30 degrees.
    mapView.setTilt(80.0f);

    // Activate some mapview options to make it smoother - optional
    mapView.getOptions().setPreloading(true);
    mapView.getOptions().setSeamlessHorizontalPan(true);
    mapView.getOptions().setTileFading(true);
    mapView.getOptions().setKineticPanning(true);
    mapView.getOptions().setDoubleClickZoomIn(true);
    mapView.getOptions().setDualClickZoomOut(true);

    // set sky bitmap - optional, default - white
    mapView.getOptions().setSkyDrawMode(Options.DRAW_BITMAP);
    mapView.getOptions().setSkyOffset(4.86f);
    mapView
        .getOptions()
        .setSkyBitmap(UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.sky_small));

    // Map background, visible if no map tiles loaded - optional, default - white
    mapView.getOptions().setBackgroundPlaneDrawMode(Options.DRAW_BITMAP);
    mapView
        .getOptions()
        .setBackgroundPlaneBitmap(
            UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.background_plane));
    mapView.getOptions().setClearColor(Color.WHITE);

    // configure texture caching - optional, suggested
    mapView.getOptions().setTextureMemoryCacheSize(40 * 1024 * 1024);
    mapView.getOptions().setCompressedMemoryCacheSize(8 * 1024 * 1024);

    // define online map persistent caching - optional, suggested. Default - no caching
    mapView.getOptions().setPersistentCachePath(this.getDatabasePath("mapcache").getPath());
    // set persistent raster cache limit to 100MB
    mapView.getOptions().setPersistentCacheSize(100 * 1024 * 1024);

    // Bounds bounds = new Bounds(57.0750, 23.8799, 56.8219, 24.3743);
    // mapView.getConstraints().setMapBounds(bounds);

    Range zoomRange = new Range(8f, 16f);
    mapView.getConstraints().setZoomRange(zoomRange);
    // 4. Start the map - mandatory
    mapView.startMapping();

    Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.pietura);
    MarkerLayer markerLayer = new MarkerLayer(mapLayer.getProjection());

    int rawResId =
        getResources()
            .getIdentifier(
                KarteActivity.transporta_tips
                    + "_"
                    + KarteActivity.marsruta_nr
                    + "_"
                    + KarteActivity.virziens,
                "raw",
                getPackageName());
    InputStream instream = getResources().openRawResource(rawResId);
    JSONObject routes = null;
    String sRawData = "";
    try {
      routes = Io.getJson(instream);
    } catch (JSONException e) {
      e.printStackTrace();
    }
    try {
      sRawData = routes.getString("raw_data");
    } catch (JSONException e) {
      e.printStackTrace();
    }
    Log.warning("sRawData: " + sRawData);
    String[] aRawData = sRawData.split(";");
    Log.warning("aRawData: " + aRawData);
    Log.warning("skaits:" + aRawData.length);
    int i;
    List<String> aPieturuId = new ArrayList<String>();
    for (i = 16; i <= aRawData.length - 1; i++ /*String sPieturasId: aRawData*/) {

      String sPieturasId = aRawData[i];
      Log.warning("id: " + sPieturasId);
      aPieturuId.add(sPieturasId);
    }
    Log.warning("pieturu id: " + aPieturuId.toString());
    // List<Pietura> pieturas = this.getStops2(aPieturuId);
    // Log.warning("pieturas: "+pieturas.toString());

    /*for (Pietura pietura : pieturas) {
    MarkerStyle markerStyle = MarkerStyle.builder().setBitmap(pointMarker).setSize(0.5f).setColor(Color.GREEN).build();
           Label markerLabel = new DefaultLabel(pietura.Name, pietura.Name);
           MapPos markerLocation = mapLayer.getProjection().fromWgs84(pietura.Lng, pietura.Lat);
           markerLayer.add(new Marker(markerLocation, markerLabel, markerStyle, null));
    }*/

    JSONObject pieturas = this.getStops3(aPieturuId);
    Iterator<String> iter = pieturas.keys();
    while (iter.hasNext()) {

      String pieturas_id = (String) iter.next();
      JSONObject pietura;
      try {
        pietura = pieturas.getJSONObject(pieturas_id);
        MarkerStyle markerStyle =
            MarkerStyle.builder().setBitmap(pointMarker).setSize(0.5f).build();
        Label markerLabel = new DefaultLabel(pietura.getString("name"));
        MapPos markerLocation =
            mapLayer.getProjection().fromWgs84(pietura.getDouble("lng"), pietura.getDouble("lat"));
        markerLayer.add(new Marker(markerLocation, markerLabel, markerStyle, null));
      } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    // add layer to the map
    mapView.getLayers().addLayer(markerLayer);

    // add event listener
    MapEventListener mapListener = new MapEventListener(this, mapView);
    mapView.getOptions().setMapListener(mapListener);

    // add GPS My Location functionality
    MyLocationCircle locationCircle = new MyLocationCircle();
    mapListener.setLocationCircle(locationCircle);
    initGps(locationCircle);
  }