如何获取用户的当前位置?

时间:2019-01-28 16:06:30

标签: javascript api mapbox mapbox-gl-js mapbox-gl

我正在设置一张地图,使商店位置更接近用户的当前位置。但是我无法做到这一点。我浏览了文档,但找不到关于我的问题的任何帮助。我想要的是如果我单击查找位置,那么它应该向我显示离我最近的商店。

我已经尝试过放置静态经度和纬度,并且效果很好。我希望它是动态的。

mapboxgl.accessToken = 'pk.eyJ1Ijoic3VzaGlsa29rYXRlIiwiYSI6ImNqcmVxeDVqeDA0c2c0NHNjcGM0Yzg4YmwifQ.NKebcVLWrkSssYyLp26Lnw';

// This adds the map to your page

var map = new mapboxgl.Map({
// container id specified in the HTML
  container: 'map',

   // style URL
  style: 'mapbox://styles/mapbox/light-v10',

 // initial position in [lon, lat] format
  center: [78.3430302, 17.449968],

 // initial zoom

 zoom: 14
});

在中心,我想要动态的经度和纬度值(当前位置)。以便向我显示离我的位置最近的商店。

3 个答案:

答案 0 :(得分:3)

Javascript具有一个地理定位API,您可以在不导入其他依赖项的情况下使用它,该API将为您提供纬度和经度方面的用户位置,您可以查看更多信息here

用户将必须授予Web应用程序访问其位置的权限。有关如何在代码中获取坐标的快速示例:

if ("geolocation" in navigator) { 
    navigator.geolocation.getCurrentPosition(position => { 
        console.log(position.coords.latitude, position.coords.longitude); 
    }); 
} else { /* geolocation IS NOT available, handle it */ }

更新:将地理位置代码合并到您的代码中将是这样的(检查它是否以纬度,经度或其他方式出现):

mapboxgl.accessToken = 'pk.eyJ1Ijoic3VzaGlsa29rYXRlIiwiYSI6ImNqcmVxeDVqeDA0c2c0NHNjcGM0Yzg4YmwifQ.NKebcVLWrkSssYyLp26Lnw';

// This adds the map to your page

if ("geolocation" in navigator) { 
    navigator.geolocation.getCurrentPosition(position => { 
        var map = new mapboxgl.Map({
        // container id specified in the HTML
          container: 'map',

           // style URL
          style: 'mapbox://styles/mapbox/light-v10',

         // initial position in [lon, lat] format
          center: [position.coords.longitude, position.coords.latitude],

         // initial zoom

         zoom: 14
        });
    }); 
} else { /* geolocation IS NOT available, handle it */ }

答案 1 :(得分:1)

其他解决方案也不错,但是最简单的方法是使用Mapbox的GeolocateControl插件。这里有一个完整的示例:https://docs.mapbox.com/mapbox-gl-js/example/locate-user/

初始设置后,它很简单:

map.addControl(new mapboxgl.GeolocateControl({
  positionOptions: {
    enableHighAccuracy: true
  },
    trackUserLocation: true
}));

答案 2 :(得分:0)

struct SegmentMenuPicker: View {
    var titles: [String]
    var color: Color
    
    @State private var selectedIndex = 0
    @State private var frames = Array<CGRect>(repeating: .zero, count: 5)

    var body: some View {
        VStack {
            ZStack {
                HStack(spacing: 10) {
                    ForEach(self.titles.indices, id: \.self) { index in
                        Button(action: {
                            print("button\(index) pressed")
                            self.selectedIndex = index
                        }) {
                            Text(self.titles[index])
                                .foregroundColor(color)
                                .font(.footnote)
                                .fontWeight(.semibold)
                        }
                        .padding(EdgeInsets(top: 0, leading: 5, bottom: 0, trailing: 5))
                        .modifier(FrameModifier())
                        .onPreferenceChange(FramePreferenceKey.self) { self.frames[index] = $0 }
                    }
                }
                .background(
                    Rectangle()
                        .fill(self.color.opacity(0.4))
                        .frame(
                            width: self.frames[self.selectedIndex].width,
                            height: 2,
                            alignment: .topLeading)
                        .offset(x: self.frames[self.selectedIndex].minX - self.frames[0].minX, y: self.frames[self.selectedIndex].height)
                    , alignment: .leading
                )
            }
            .padding(.bottom, 15)
            .animation(.easeIn(duration: 0.2))

            Text("Value: \(self.titles[self.selectedIndex])")
            Spacer()
        }
    }
}

struct FramePreferenceKey: PreferenceKey {
    static var defaultValue: CGRect = .zero

    static func reduce(value: inout CGRect, nextValue: () -> CGRect) {
        value = nextValue()
    }
}

struct FrameModifier: ViewModifier {
    private var sizeView: some View {
        GeometryReader { geometry in
            Color.clear.preference(key: FramePreferenceKey.self, value: geometry.frame(in: .global))
        }
    }

    func body(content: Content) -> some View {
        content.background(sizeView)
    }
}

struct NewPicker_Previews: PreviewProvider {
    static var previews: some View {
        VStack {
            SegmentMenuPicker(titles: ["SuperLongValue", "1", "2", "Medium", "AnotherSuper"], color: Color.blue)
            NavigationView {
                SegmentMenuPicker(titles: ["SuperLongValue", "1", "2", "Medium", "AnotherSuper"], color: Color.red)
            }
        }
    }
}
if ( navigator.geolocation ) 
{
    navigator.geolocation.getCurrentPosition( function(position) {

        var lng = position.coords.longitude;
        var lat = position.coords.latitude;                    

        mapboxgl.accessToken = 'pk.eyJ1IjoiYW50ZWxvdmUxOSIsImEiOiJja2d1azl4ZmgwY3dvMnJueGljMnp6YnprIn0.aIRE0Ii2AmWYWCW5Z3cEFg';

        var map = new mapboxgl.Map({
            container: 'map',          
            style: 'mapbox://styles/mapbox/streets-v11',
            center: [ lng, lat ], // [ lng, lat ]
            zoom: 12
        });

    });
}
body { margin: 0; padding: 0; }
#map { position: absolute; top: 0; bottom: 0; width: 100%; }

相关问题