Показать FloorPlan и получить местоположение с помощью IndoorAtlas

Есть ли какой-нибудь ресурс о том, как использовать IndoorAtlas SDK?

Я не понимаю, как показать план этажа и получить текущее местоположение.

Пожалуйста, помогите мне.


person Leonard Febrianto    schedule 28.04.2015    source источник


Ответы (1)


Вот очень примерно как:

1) Инициализировать экземпляр IndoorAtlas:

IndoorAtlas ia = IndoorAtlasFactory.createIndoorAtlas(context, listener, apiKey, apiSecret);

2) Получите экземпляр FloorPlan:

FutureResult<FloorPlan> result = ia.fetchFloorPlan(floorPlanId);
result.setCallback(new ResultCallback<FloorPlan>() {
            @Override
            public void onResult(final FloorPlan result) {
                mFloorPlan = result;
                loadFloorPlanImage(result);
            }
            // handle error conditions too
}

3) Получить фактическое изображение:

void loadFloorPlanImage(FloorPlan floorPlan) {
  BitmapFactory.Options options = createBitmapOptions(floorPlan);
  FutureResult<Bitmap> result = ia.fetchFloorPlanImage(floorPlan, options);
  result.setCallback(new ResultCallback<Bitmap>() {
            @Override
            public void onResult(final Bitmap result) {
               // now you have floor plan bitmap, do something with it
               updateImageViewInUiThread(result);
            }
            // handle error conditions too
  }
}

4) Начать позиционирование:

ia.startPositioning(venueId, floorId, floorPlanId);

5) Показать позиции на плане этажа:

public void onServiceUpdate(ServiceState state) {

   // get position on original floor plan image
   int i = state.getImagePoint().getI();
   int j = state.getImagePoint().getJ();

   // take into account how your floor plan image has been scaled
   // and draw position
   PointF scaledPoint = new PointF();
   Util.calculateScaledPoint((int) floorPlan.dimensions[0], (int) floorPlan.dimensions[1], i, j, mImageView, scaledPoint);

   drawNewPositionInUiThread(scaledPoint.x, scaledPoint.y);

}

Конечно, вы можете сначала начать позиционирование, а затем уже получать изображение. Вы также можете кэшировать изображение локально, но, как уже говорилось, примерно так.

Утил.java:

public class Utils {


    /**
     * Calculates scaling factor for an image with original dimensions of
     * {@code originalWidth x originalHeight} being displayed with {@code imageView}.
     *
     * The assumption with this example code is that a) layout has been already performed for
     * {@code imageView} and that {@link android.widget.ImageView.ScaleType#CENTER_INSIDE} is used.
     *
     * @param originalWidth  height of the original bitmap to be displayed using {@code imageView}
     * @param originalHeight width of the original bitmap to be displayed using {@code imageView}
     */
    public static float calculateScaleFactor(int originalWidth, int originalHeight,
                                             ImageView imageView) {

        if (imageView.getScaleType() != ImageView.ScaleType.CENTER_INSIDE) {
            throw new IllegalArgumentException("only scale type of CENTER_INSIDE supported, was: "
                    + imageView.getScaleType());
        }

        final int availableX = imageView.getWidth()
                - (imageView.getPaddingLeft() + imageView.getPaddingRight());
        final int availableY = imageView.getHeight()
                - (imageView.getPaddingTop() + imageView.getPaddingBottom());

        if (originalWidth > availableX || originalHeight > availableY) {
            // original image would not fit without scaling
            return originalWidth > availableX
                    ? availableX / (float) originalWidth
                    : availableY / (float) originalHeight;
        } else {
            return 1f; // no scaling required
        }

    }


    /**
     * Calculates point where to draw coordinates {@code x} and {@code y} in a bitmap that's
     * original dimensions were {@code originalWidth x originalHeight} and may now be scaled down
     * as it's been displayed with {@code imageView}.
     *
     * @param originalWidth  width of the original bitmap before any scaling
     * @param originalHeight height of the original bitmap before any scaling
     * @param x              x-coordinate on original bitmap
     * @param y              y-coordinate on original bitmap
     * @param imageView      view that will be used to display bitmap
     * @param point          point where result value is to be stored
     * @see #calculateScaleFactor(int, int, ImageView)
     */
    public static void calculateScaledPoint(int originalWidth, int originalHeight,
                                            int x, int y,
                                            ImageView imageView,
                                            PointF point) {


        final float scale = calculateScaleFactor(originalWidth, originalHeight, imageView);
        final float scaledWidth = originalWidth * scale;
        final float scaledHeight = originalHeight * scale;

        // when image inside view is smaller than the view itself and image is centered (assumption)
        // there will be some empty space around the image (here offset)
        final float offsetX = Math.max(0, (imageView.getWidth() - scaledWidth) / 2);
        final float offsetY = Math.max(0, (imageView.getHeight() - scaledHeight) / 2);

        point.x = offsetX + (x * scale);
        point.y = offsetY + (y * scale);


    }


}
person Jukka Raanamo    schedule 28.04.2015
comment
Спасибо за ваш ответ. Я на нем. Но для номера 1, как вы объявляете слушателя? IndoorAtlasListener или другой слушатель? - person Leonard Febrianto; 29.04.2015
comment
Да, IndoorAtlasListener. Базовый пример этого можно найти в примере приложения, которое поставляется с IndoorAtlas SDK. - person Jukka Raanamo; 29.04.2015
comment
Возможно, я не понимаю, как объявить: loadFloorPlanImage,updateImageViewInUiThread,drawNewPositionInUiThread. Не могли бы вы направить меня? Спасибо перед - person Leonard Febrianto; 29.04.2015
comment
loadFloorPlanImage: это был шаг 3) (я обновляю ответ сигнатурой метода). updateImageViewInUiThread: может быть таким же простым, как назначение растрового изображения ImageView, но вам нужно сделать это в основном потоке, например. developer.android.com/reference/android /приложение/. drawNewPositionInUiThread: здесь вы можете рисовать, например. круг на холсте в месте вашего нового местоположения. Я постараюсь найти время, чтобы сделать полный пример. - person Jukka Raanamo; 29.04.2015
comment
Это было более ясно. Извините, что забыл упомянуть «createBitmapOptions». что внутри в этом методе? - person Leonard Febrianto; 29.04.2015
comment
Здравствуйте @LeonardFebrianto, не могли бы вы подсказать мне, что такое значение для плана этажа, как получить изображение из приложения? Я застрял в этом. - person Apurva Agrawal; 28.07.2015
comment
Пожалуйста, сделайте это под вопросом и дайте мне ссылку. Так что я могу ответить в вашей теме. - person Leonard Febrianto; 29.07.2015
comment
HI Всем нужна помощь, чтобы завершить мой код. Я тоже использовал IndoorAtlas, но, похоже, у меня ничего не вышло. Моя проблема в том, что я не могу показать загруженную карту с сервера inddoratlas и не могу отметить положение пользователя. Пожалуйста, помогите решить эти проблемы. - person Arpana; 13.08.2015
comment
не могли бы вы опубликовать полный код, чтобы все было правильно. Я нахожусь на полпути, загрузил и отобразил план этажа, но не могу идти дальше. как поставить точку на этом. - person Ansal Ali; 12.10.2015