如何在设备方向上平稳旋转地图

时间:2020-06-12 06:34:59

标签: javascript android-webview mapbox mapbox-gl-js device-orientation

我正在android webview中使用deviceorientationabsolute将地图旋转到设备指向的方向。我正在使用mapbox-gl js。

问题在于,即使设备在移动后仍然保持静止,地图也会持续旋转一段时间。同样,当设备保持原样时,地图仍会旋转,这使其看起来非常生涩。我希望旋转平稳而不滞后。

有人可以帮我吗?

Here is an video of what is happening on my device

这是我的代码: JS

var longitude, latitude, diff, map;
var interval = 5000; // initial condition




var alpha;
window.addEventListener("deviceorientationabsolute", manageCompass, false);


function manageCompass(event) {
    if (event.webkitCompassHeading) {
        absoluteHeading = event.webkitCompassHeading + 180;
    } else {
        absoluteHeading = 180 - event.alpha;
    }
    console.log(absoluteHeading);
    alpha = absoluteHeading;
    if(parseInt(alpha) < 0){
      alpha = 360 - (360+alpha);
    }else if(parseInt(alpha) > 0){
      alpha = 360 - alpha;
    }

    if(parseInt(alpha) >=0 && parseInt(alpha) <= 180){
      alpha = 180-alpha;
    }else if(parseInt(alpha) >= 181 && parseInt(alpha) <= 359){
      alpha = 360 + (180 - alpha);
    }
    if(map != undefined){
       map.rotateTo(alpha,{duration:5});
    }
    document.getElementById("info").innerHTML = JSON.stringify(parseInt(alpha));


}


$(document).ready(function(){

  longitude = 77.125959;
  latitude =  28.707724;
  showmap();
});


function showmap(callback){
    mapboxgl.accessToken = 'pk.eyJ1IjoibWFzaDEyIiwiYSI6ImNrNzBhMHc2aTFhMnkza3J2OG51azV6aW0ifQ.1FeBAzRjqkSQex-u-GiPyw';
    map = new mapboxgl.Map({
        style: 'mapbox://styles/mapbox/streets-v11',
        center: [longitude,latitude],
        zoom: 17.6,
        pitch: 95,
        bearing: -17.6,
        container: 'map',
        antialias: false,
        dragPan: false,
        dragRotate: false,
        maxZoom: 18.4,
        minZoom: 17.3
    });

    var geojson = {
            'type': 'FeatureCollection',
            'features': [
              {
                'type': 'Feature',
                'geometry': {
                  'type': 'Point',
                  'coordinates': [longitude,latitude]
                },
                'properties': {
                  'title': 'Mapbox',
                  'description': 'Park Centra'
                }
              }
            ]
          };



    map.on('rotate',function(){
        map.jumpTo({center: [longitude,latitude]});
    });

    map.on('load', function() {
        // Insert the layer beneath any symbol layer.
        console.log("map loaded");
        var layers = map.getStyle().layers;
        console.log(layers);

        var labelLayerId;
        for (var i = 0; i < layers.length; i++) {
            if (layers[i].type === 'symbol' && layers[i].layout['text-field']) {
                labelLayerId = layers[i].id;
                break;
            }
        }

        map.addLayer(
            {
                'id': '3d-buildings',
                'source': 'composite',
                'source-layer': 'building',
                'filter': ['==', 'extrude', 'true'],
                'type': 'fill-extrusion',
                'minzoom': 15,
                'paint': {
                    'fill-extrusion-color': '#aaa',

                    // use an 'interpolate' expression to add a smooth transition effect to the
                    // buildings as the user zooms in
                    'fill-extrusion-height': [
                        'interpolate',
                        ['linear'],
                        ['zoom'],
                        15,
                        0,
                        15.05,
                        ['get', 'height']
                    ],
                    'fill-extrusion-base': [
                        'interpolate',
                        ['linear'],
                        ['zoom'],
                        15,
                        0,
                        15.05,
                        ['get', 'min_height']
                    ],
                    'fill-extrusion-opacity': 0.6
                }
            },
            labelLayerId
        );


});
}

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Device Rotation</title>
    <meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.js"></script>
    <link href="https://api.mapbox.com/mapbox-gl-js/v1.9.1/mapbox-gl.css" rel="stylesheet" />
    <style>
    body { margin: 0; padding: 0; }
    #map { position: absolute; top: 0; bottom: 0; width: 100%; }
    #info {
          display: block;
          position: relative;
          margin: 0px auto;
          width: 50%;
          padding: 10px;
          border: none;
          border-radius: 3px;
          font-size: 12px;
          text-align: center;
      }
    </style>
</head>
<body>
<div id="map"></div>
<pre id="info"></pre>
<script src = "js/test.js"> </script>
</body>
</html>

MainActivity.java

public class MainActivity extends AppCompatActivity {

    WebView webView;
    MainActivity mainActivity ;
    private Context mContext;
    private Geocoder geocoder;

    public static final int MY_PERMISSIONS_REQUEST_ACCESS_LOCATION = 200;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
        setContentView(R.layout.activity_main);

        webView = (WebView)findViewById(R.id.mybrowser);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebChromeClient(new MyWebLogger());

        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        webView.setScrollbarFadingEnabled(false);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setGeolocationEnabled(true);


        webView.loadUrl("file:///android_asset/test.html");


        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url != null) view.loadUrl(url);
                return true;
            }
        });



    }

}

0 个答案:

没有答案