Kotlin - шестиугольная ручка Google Maps API v3 - оптимизировать код - PullRequest
0 голосов
/ 21 февраля 2019

Мне нужна помощь для оптимизации моего кода.Несмотря на то, что это работает, я чувствую сильное чувство, это может быть сделано в ПУТИ меньше строк кода и гораздо более эффективным.Но я не могу понять это сам.

На самом деле это еще даже не работает идеально.

У меня есть маркер в центре.Я хочу, чтобы этот центр был центром шестиугольной сетки многоугольников поверх Карт Google.

В настройках приложений пользователь может установить количество шестиугольников, которые он хочет иметь на севере, востоке, западе и юге.направление.Поэтому я хочу нарисовать все эти шестиугольники, начиная с моего центра HEX Grid.

Здесь вы найдете мой код, который дает мне что-то, но не совсем правильную вещь.

private fun drawHexagonGrid(){
        var radius = 3.5  //radius in metre
        var curPos = heartAlveole  //hierdann Heart Alveole aus den Prefs nehmen
        var northAlveoles = 5  //Das alles aus den Prefs holen.
        var eastAlveoles = 10
        var southAlveoles = 5
        var westAlveoles = 5
        val width = radius.toDouble() * 2.0 * Math.sqrt(3.0) / 2


        //North East of Heart

        curPos = heartAlveole
        for (n in 0..northAlveoles){
            //East Alveoles
            for (i in 0..eastAlveoles) {
                drawHorizontalHexagon(curPos, radius, ".")
                curPos = SphericalUtil.computeOffset(curPos, width,90.0);
            }
            curPos = SphericalUtil.computeOffset(curPos, width*eastAlveoles,270.0)
            //Every Second Iteration go half width west or east
            if (n % 2 == 0) {
                curPos = SphericalUtil.computeOffset(curPos, width/2,270.0)
            }
            else {
                curPos = SphericalUtil.computeOffset(curPos, width/2,90.0)
            }
            //go north
            curPos = SphericalUtil.computeOffset(curPos,5.25 ,0.0)

        }

        //North West of Heart

        curPos = heartAlveole
        for (n in 0..northAlveoles){
            //East Alveoles
            for (i in 0..westAlveoles) {
                drawHorizontalHexagon(curPos, radius, ".")
                curPos = SphericalUtil.computeOffset(curPos, width,270.0);
            }
            curPos = SphericalUtil.computeOffset(curPos, width*westAlveoles,90.0)

            //Every Second Iteration go half width west or east
            if (n % 2 == 0) {
                curPos = SphericalUtil.computeOffset(curPos, width/2,270.0)
            }
            else {
                curPos = SphericalUtil.computeOffset(curPos, width/2,90.0)
            }
            //go north
            curPos = SphericalUtil.computeOffset(curPos,5.25 ,0.0)

        }

        //South East of Heart

        curPos= heartAlveole
        for (n in 0..southAlveoles){
            //Every Second Iteration go half width west or east
            if (n % 2 == 0) {
                curPos = SphericalUtil.computeOffset(curPos, width/2,270.0)
            }
            else {
                curPos = SphericalUtil.computeOffset(curPos, width/2,90.0)
            }
            //go south
            curPos = SphericalUtil.computeOffset(curPos,5.25 ,180.0)
            //East Alveoles
            for (i in 0..eastAlveoles) {
                drawHorizontalHexagon(curPos, radius, ".")
                curPos = SphericalUtil.computeOffset(curPos, width,90.0);
            }

            curPos = SphericalUtil.computeOffset(curPos, width*eastAlveoles,270.0)


        }

        //South West of Heart

        curPos= heartAlveole
        for (n in 0..southAlveoles){
            //Every Second Iteration go half width west or east
            if (n % 2 == 0) {
                curPos = SphericalUtil.computeOffset(curPos, width/2,270.0)
            }
            else {
                curPos = SphericalUtil.computeOffset(curPos, width/2,90.0)
            }
            //go south
            curPos = SphericalUtil.computeOffset(curPos,5.25 ,180.0)
            //West Alveoles
            for (i in 0..westAlveoles) {
                drawHorizontalHexagon(curPos, radius, ".")
                curPos = SphericalUtil.computeOffset(curPos, width,270.0);
            }

            curPos = SphericalUtil.computeOffset(curPos, width*westAlveoles,90.0)

        }



    }

    private fun drawHorizontalHexagon(position : LatLng, radius : Double, label : String){
        var coordinates : MutableList<LatLng> = arrayListOf()

        for (angle in 0..360 step 60) {
            coordinates.add(SphericalUtil.computeOffset(position,radius,angle.toDouble()))
        }

        var opts : PolygonOptions = PolygonOptions().addAll(coordinates)
            .fillColor(Color.argb(35,255, 0,0))
            .strokeColor(Color.RED).strokeWidth(3f)

        mMap.addPolygon(opts)


        //Funktioniert theoretisch. Noch überlegen ob ich es wirklich brauche.
        //Müsste noch das Transparent ändern und die Größe der Schrift anpassen.
        //this.showText(position, label)

    }

Как видите, у меня есть функция drawHexagon.А также некоторые функции Looping.Идя на юг, вы должны перемещаться по полуширине влево или вправо.Это не так тривиально, как кажется;)

Спасибо за вашу помощь!

1 Ответ

0 голосов
/ 21 февраля 2019

Я нашел ответ сам.Я опубликую это здесь для архива, если у кого-то есть та же самая проблема.

private fun drawHexagonGrid(){
    var radius = 3.5  //radius in metre
    var curPos = heartAlveole  //hierdann Heart Alveole aus den Prefs nehmen
    var northAlveoles = 5  //Das alles aus den Prefs holen.
    var eastAlveoles = 10
    var southAlveoles = 5
    var westAlveoles = 5
    val width = radius.toDouble() * 2.0 * Math.sqrt(3.0) / 2


    //Move to NorthWest Corner of HexGrid

    val westMove = if (northAlveoles % 2 == 0) width*westAlveoles else (width*westAlveoles)-(width/2)

    //If northAlveoles is unequal, add half width to westMove to

    curPos = SphericalUtil.computeOffset(curPos,westMove,270.0)
    curPos = SphericalUtil.computeOffset(curPos,radius * 6/4*northAlveoles,0.0)

    //nested for loop to produce hexagonal grid

    for (n in 1..northAlveoles+southAlveoles+1){
        //draw horizontal hexagons
        for (e in 1..eastAlveoles+westAlveoles+1) {
            drawHorizontalHexagon(curPos, radius, ".")
            curPos = SphericalUtil.computeOffset(curPos, width,90.0);
        }

        //Go back to the initial position + width/2 or - width/2 every second iteration
        if (n % 2 == 0) {
            curPos = SphericalUtil.computeOffset(curPos, width*((westAlveoles+eastAlveoles)+0.5),270.0)
        } else {
            curPos = SphericalUtil.computeOffset(curPos, width*((westAlveoles+eastAlveoles)+1.5),270.0)
        }
        //go south
        curPos = SphericalUtil.computeOffset(curPos,radius * 6/4 ,180.0)
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...