// Map View manipulation handlers
  @Override
  public void onMapClicked(final double x, final double y, final boolean longClick) {
    // x and y are in base map projection, we convert them to the familiar
    // WGS84
    Log.debug(
        "onMapClicked "
            + (new EPSG3857()).toWgs84(x, y).x
            + " "
            + (new EPSG3857()).toWgs84(x, y).y
            + " longClick: "
            + longClick);

    MutableMapPos tilePos = new MutableMapPos();
    MapTile clickedTile = mapView.worldToMapTile(x, y, tilePos);

    Log.debug("clicked tile " + clickedTile + " pos:" + tilePos);

    if (layer instanceof UtfGridLayerInterface) {

      Map<String, String> toolTips = layer.getUtfGridTooltips(clickedTile, tilePos, this.template);

      if (toolTips == null) {
        return;
      }
      Log.debug("utfGrid tooltip values: " + toolTips.size());
      updateMarker(new MapPos(x, y), toolTips);
    }
  }
  protected void initGps(final MyLocationCircle locationCircle) {
    final Projection proj = mapView.getLayers().getBaseLayer().getProjection();

    LocationListener locationListener =
        new LocationListener() {
          public void onLocationChanged(Location location) {
            if (locationCircle != null) {
              locationCircle.setLocation(proj, location);
              locationCircle.setVisible(true);
            }
          }

          public void onStatusChanged(String provider, int status, Bundle extras) {}

          public void onProviderEnabled(String provider) {}

          public void onProviderDisabled(String provider) {}
        };

    LocationManager locationManager =
        (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

    locationManager.requestLocationUpdates(
        LocationManager.NETWORK_PROVIDER, 10000, 100, locationListener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
  }
  private void updateMarker(MapPos pos, Map<String, String> toolTips) {

    if (clickMarker != null) {

      String text = "";
      if (toolTips.containsKey(UtfGridHelper.TEMPLATED_TEASER_KEY)) {
        // strio HTML from the teaser, so it can be shown in normal
        //              String strippedTeaser =
        // android.text.Html.fromHtml(toolTips.get(UtfGridHelper.TEMPLATED_TEASER_KEY).replaceAll("\\<.*?>","")).toString().replaceAll("\\p{C}", "").trim();
        //              Toast.makeText(activity, strippedTeaser, Toast.LENGTH_SHORT).show();
        //                Log.debug("show label ")
        text = toolTips.get(UtfGridHelper.TEMPLATED_TEASER_KEY);
      } else if (toolTips.containsKey("ADMIN")) {
        text = toolTips.get("ADMIN");
      }

      clickMarker.setMapPos(pos);
      mapView.selectVectorElement(clickMarker);
      WebView webView = ((WebView) ((ViewLabel) clickMarker.getLabel()).getView());
      Log.debug("showing html: " + text);
      webView.loadDataWithBaseURL(
          "file:///android_asset/",
          UiUtils.HTML_HEAD + text + UiUtils.HTML_FOOT,
          "text/html",
          "UTF-8",
          null);

      clickMarker.userData = toolTips;
    }
  }
 private void updateMarker(MapPos pos, String text) {
   if (clickMarker != null) {
     clickMarker.setMapPos(pos);
     mapView.selectVectorElement(clickMarker);
     WebView webView = ((WebView) ((ViewLabel) clickMarker.getLabel()).getView());
     Log.debug("showing html: " + text);
     webView.loadDataWithBaseURL("file:///android_asset/", text, "text/html", "UTF-8", null);
   }
 }
  @Override
  protected void onStop() {
    super.onStop();
    Log.debug("x " + getMapView().getFocusPoint().x);
    Log.debug("y " + getMapView().getFocusPoint().y);
    Log.debug("tilt " + getMapView().getTilt());
    Log.debug("rotation " + getMapView().getRotation());
    Log.debug("zoom " + getMapView().getZoom());

    mapView.stopMapping();
  }
  @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 showRoute(
      final double fromLat, final double fromLon, final double toLat, final double toLon) {

    Log.debug("calculating path " + fromLat + "," + fromLon + " to " + toLat + "," + toLon);

    Projection proj = mapView.getLayers().getBaseLayer().getProjection();
    stopMarker.setMapPos(proj.fromWgs84(toLon, toLat));

    CloudMadeDirections directionsService =
        new CloudMadeDirections(
            this,
            new MapPos(fromLon, fromLat),
            new MapPos(toLon, toLat),
            CloudMadeDirections.ROUTE_TYPE_CAR,
            CloudMadeDirections.ROUTE_TYPE_MODIFIER_FASTEST,
            CLOUDMADE_KEY,
            proj);
    directionsService.route();
  }
  // Map View manipulation handlers
  @Override
  public void onMapClicked(final double x, final double y, final boolean longClick) {
    // x and y are in base map projection, we convert them to the familiar
    // WGS84
    Log.debug(
        "onMapClicked "
            + (new EPSG3857()).toWgs84(x, y).x
            + " "
            + (new EPSG3857()).toWgs84(x, y).y
            + " longClick: "
            + longClick);

    MapPos wgs84Pos = mapView.getComponents().layers.getBaseProjection().toWgs84(x, y);
    final MapPos mapPos = dataSource.getProjection().fromWgs84(wgs84Pos.x, wgs84Pos.y);

    // perform network query to get feature info. This must be done in separate thread!
    new Thread(
            new Runnable() {
              @Override
              public void run() {
                final String featureInfo = dataSource.getFeatureInfo(mapPos);

                if (featureInfo == null) {
                  return;
                } else {
                  // update marker in UI thread
                  handler.post(
                      new Runnable() {
                        @Override
                        public void run() {
                          updateMarker(new MapPos(x, y), featureInfo);
                        }
                      });
                }
              }
            })
        .start();
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

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

    // 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);
      mapView.startMapping();
      return;
    } else {
      // 2. create and set MapView components - mandatory
      Components components = new Components();
      // set stereo view: works if you rotate to landscape and device has HTC 3D or LG Real3D
      mapView.setComponents(components);
    }

    // 3. Define map layer for basemap - mandatory.

    TMSMapLayer mapLayer =
        new TMSMapLayer(
            new EPSG3857(), 0, 18, 2, "http://otile1.mqcdn.com/tiles/1.0.0/osm/", "/", ".png");
    mapView.getLayers().setBaseLayer(mapLayer);

    // define style for 3D to define minimum zoom = 14
    ModelStyle modelStyle = ModelStyle.builder().build();
    StyleSet<ModelStyle> modelStyleSet = new StyleSet<ModelStyle>(null);
    modelStyleSet.setZoomStyle(14, modelStyle);

    // ** Online 3D Model layer

    NMLModelOnlineLayer modelLayer =
        new NMLModelOnlineLayer(
            new EPSG3857(),
            "http://aws-lb.nutiteq.ee/nml/nmlserver2.php?data=demo&",
            modelStyleSet);

    modelLayer.setMemoryLimit(20 * 1024 * 1024);

    modelLayer.setPersistentCacheSize(30 * 1024 * 1024);
    modelLayer.setPersistentCachePath(this.getDatabasePath("nmlcache").getPath());

    modelLayer.setLODResolutionFactor(0.3f);
    getMapView().getLayers().addLayer(modelLayer);

    // Tallinn
    mapView.setFocusPoint(new MapPos(2753845.7830863246f, 8275045.674995658f));

    // San Francisco
    // mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(-122.41666666667f, 37.76666666666f));

    mapView.setZoom(17.0f);

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

    // Activate some mapview options to make it smoother - optional
    mapView.getOptions().setPreloading(false);
    mapView.getOptions().setSeamlessHorizontalPan(true);
    mapView.getOptions().setTileFading(false);
    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. Start the map - mandatory
    mapView.startMapping();

    // 5. 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();
          }
        });
  }
  @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
 protected void onStop() {
   super.onStop();
   mapView.stopMapping();
 }
 @Override
 protected void onStart() {
   mapView.startMapping();
   super.onStart();
 }
  @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);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // spinner in status bar, for progress indication
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.main);

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

    // 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);
      mapView.startMapping();
      return;
    } else {
      // 2. create and set MapView components - mandatory
      Components components = new Components();
      // set stereo view: works if you rotate to landscape and device has HTC 3D or LG Real3D
      mapView.setComponents(components);
    }

    // 3. Define map layer for basemap - mandatory.

    TMSMapLayer mapLayer =
        new TMSMapLayer(
            new EPSG3857(), 5, 18, 0, "http://otile1.mqcdn.com/tiles/1.0.0/osm/", "/", ".png");
    mapView.getLayers().setBaseLayer(mapLayer);

    // define style for 3D to define minimum zoom = 14
    ModelStyle modelStyle = ModelStyle.builder().build();
    StyleSet<ModelStyle> modelStyleSet = new StyleSet<ModelStyle>(null);
    modelStyleSet.setZoomStyle(14, modelStyle);

    // ** 3D Model layer
    try {
      Bundle b = getIntent().getExtras();
      String mapFile = b.getString("selectedFile");

      NMLModelDbLayer modelLayer = new NMLModelDbLayer(new EPSG3857(), mapFile, modelStyleSet);
      modelLayer.setMemoryLimit(20 * 1024 * 1024);
      mapView.getLayers().addLayer(modelLayer);

      // set initial map view camera from database
      Envelope extent = modelLayer.getDataExtent();

      DisplayMetrics metrics = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(metrics);
      int screenHeight = metrics.heightPixels;
      int screenWidth = metrics.widthPixels;

      double zoom =
          Math.log(
                  (screenWidth * (Math.PI * 6378137.0f * 2.0f))
                      / ((extent.maxX - extent.minX) * 256.0))
              / Math.log(2);

      MapPos centerPoint =
          new MapPos((extent.maxX + extent.minX) / 2, (extent.maxY + extent.minY) / 2);
      Log.debug("found extent " + extent + ", zoom " + zoom + ", centerPoint " + centerPoint);

      mapView.setZoom((float) zoom);
      mapView.setFocusPoint(centerPoint);

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

    // 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(false);
    mapView.getOptions().setSeamlessHorizontalPan(true);
    mapView.getOptions().setTileFading(false);
    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. Start the map - mandatory
    mapView.startMapping();

    // 5. 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();
          }
        });
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.main);

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

    // 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);
      mapView.startMapping();
      return;
    } else {
      // 2. create and set MapView components - mandatory
      Components components = new Components();
      // set stereo view: works if you rotate to landscape and device has HTC 3D or LG Real3D
      mapView.setComponents(components);
    }

    // 3. Define map layer for basemap - mandatory.
    TMSMapLayer mapLayer =
        new TMSMapLayer(
            new EPSG3857(),
            0,
            18,
            3,
            //				"http://nutiteq.cartodb.com/tiles/tm_world_borders/", "/", ".png");
            "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: Estonia
    // mapView.setFocusPoint(mapView.getLayers().getBaseLayer().getProjection().fromWgs84(24.5f,
    // 58.3f));
    mapView.setFocusPoint(new MapPos(2745202.3f, 8269676.0f));
    // rotation - 0 = north-up
    mapView.setRotation(0f);
    // zoom - 0 = world, like on most web maps
    mapView.setZoom(9.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(false);
    mapView.getOptions().setSeamlessHorizontalPan(true);
    mapView.getOptions().setTileFading(false);
    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();
          }
        });

    // 5. Add CartoDB vector layer to map

    //  5.1 Define styles for all possible geometry types

    int minZoom = 5;
    int color = Color.BLUE;

    StyleSet<PointStyle> pointStyleSet = new StyleSet<PointStyle>();
    Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.point);
    PointStyle pointStyle =
        PointStyle.builder()
            .setBitmap(pointMarker)
            .setSize(0.05f)
            .setColor(color)
            .setPickingSize(0.2f)
            .build();
    pointStyleSet.setZoomStyle(minZoom, pointStyle);

    StyleSet<LineStyle> lineStyleSet = new StyleSet<LineStyle>();
    LineStyle lineStyle = LineStyle.builder().setWidth(0.04f).setColor(Color.WHITE).build();
    lineStyleSet.setZoomStyle(minZoom, lineStyle);

    PolygonStyle polygonStyle =
        PolygonStyle.builder().setColor(0xFFFF6600 & 0x80FFFFFF).setLineStyle(lineStyle).build();
    StyleSet<PolygonStyle> polygonStyleSet = new StyleSet<PolygonStyle>(null);
    polygonStyleSet.setZoomStyle(minZoom, polygonStyle);

    StyleSet<LineStyle> roadLineStyleSet =
        new StyleSet<LineStyle>(LineStyle.builder().setWidth(0.07f).setColor(0xFFAAAAAA).build());

    //  5.2 Define layer and add to map

    String account = "nutiteq";
    String table = "tm_world_borders"; // kihelkonnad_1897, maakond_20120701
    String columns =
        "name,iso2,pop2005,area,"
            + CartoDbVectorLayer.TAG_WEBMERCATOR; // NB! always include the_geom_webmercator
    int limit = 5000; // max number of objects
    String sql =
        "SELECT "
            + columns
            + " FROM "
            + table
            + " WHERE "
            + CartoDbVectorLayer.TAG_WEBMERCATOR
            + " && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT "
            + limit;

    //      String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads
    // WHERE type in ('trunk','primary') AND the_geom_webmercator &&
    // ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";
    //      String sql2 = "SELECT name, type, oneway, osm_id, the_geom_webmercator FROM osm_roads
    // WHERE the_geom_webmercator && ST_SetSRID('BOX3D(!bbox!)'::box3d, 3857) LIMIT 500";
    CartoDbVectorLayer cartoLayerTrunk =
        new CartoDbVectorLayer(
            mapView.getLayers().getBaseLayer().getProjection(),
            account,
            sql,
            pointStyleSet,
            lineStyleSet,
            polygonStyleSet);
    mapView.getLayers().addLayer(cartoLayerTrunk);

    //		CartoDbVectorLayer cartoLayer = new
    // CartoDbVectorLayer(mapView.getLayers().getBaseLayer().getProjection(), account, sql,
    // pointStyleSet, lineStyleSet, polygonStyleSet);

    //      OnlineVectorLayer vectorLayer = new
    // OnlineVectorLayer(mapView.getLayers().getBaseLayer().getProjection(), pointStyleSet,
    // lineStyleSet, polygonStyleSet,2000);
    //		mapView.getLayers().addLayer(vectorLayer);
  }
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // spinner in status bar, for progress indication
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

    setContentView(R.layout.main);

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

    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    dpi = metrics.density;

    // 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);
      return;
    } else {
      // 2. create and set MapView components - mandatory
      Components components = new Components();
      // set stereo view: works if you rotate to landscape and device has
      // HTC 3D or LG Real3D
      mapView.setComponents(components);
    }

    // 3. Define map layer for basemap - mandatory.
    // read filename from extras
    Bundle b = getIntent().getExtras();
    String mapFilePath = b.getString("selectedFile");

    XmlRenderTheme renderTheme = InternalRenderTheme.OSMARENDER;
    // XmlRenderTheme renderTheme = new AssetsRenderTheme(this, "",
    // "renderthemes/assets_noname.xml");

    MapDatabase mapDatabase = new MapDatabase();
    mapDatabase.closeFile();
    File mapFile = new File("/" + mapFilePath);
    FileOpenResult fileOpenResult = mapDatabase.openFile(mapFile);
    if (fileOpenResult.isSuccess()) {
      Log.debug("MapsforgeRasterDataSource: MapDatabase opened ok: " + mapFilePath);
    }

    MapsforgeRasterDataSource dataSource =
        new MapsforgeRasterDataSource(
            new EPSG3857(), 0, 20, mapFile, mapDatabase, renderTheme, this.getApplication());
    RasterLayer mapLayer = new RasterLayer(dataSource, 1044);
    mapView.getLayers().setBaseLayer(mapLayer);

    // set initial map view camera from database
    MapFileInfo mapFileInfo = dataSource.getMapDatabase().getMapFileInfo();
    if (mapFileInfo != null) {
      if (mapFileInfo.startPosition != null && mapFileInfo.startZoomLevel != null) {
        // start position is defined
        MapPos mapCenter =
            new MapPos(
                mapFileInfo.startPosition.longitude,
                mapFileInfo.startPosition.latitude,
                mapFileInfo.startZoomLevel);
        Log.debug("center: " + mapCenter);
        mapView.setFocusPoint(
            mapView.getLayers().getBaseLayer().getProjection().fromWgs84(mapCenter.x, mapCenter.y));
        mapView.setZoom((float) mapCenter.z);
      } else if (mapFileInfo.boundingBox != null) {
        // start position not defined, but boundingbox is defined
        MapPos boxMin =
            mapView
                .getLayers()
                .getBaseLayer()
                .getProjection()
                .fromWgs84(
                    mapFileInfo.boundingBox.minLongitude, mapFileInfo.boundingBox.minLatitude);
        MapPos boxMax =
            mapView
                .getLayers()
                .getBaseLayer()
                .getProjection()
                .fromWgs84(
                    mapFileInfo.boundingBox.maxLongitude, mapFileInfo.boundingBox.maxLatitude);
        mapView.setBoundingBox(new Bounds(boxMin.x, boxMin.y, boxMax.x, boxMax.y), true);
      }
    }

    // if no fileinfo, startPosition or boundingBox, then remain to default
    // world view

    // rotation - 0 = north-up
    mapView.setMapRotation(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(false);
    mapView.getOptions().setSeamlessHorizontalPan(true);
    mapView.getOptions().setTileFading(false);
    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(16 * 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);

    mapView.getOptions().setRasterTaskPoolSize(1);

    // 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();
          }
        });
  }