Using MapBox for Geolocation in html

眉间皱痕 提交于 2019-12-01 10:46:34

mapbox-gl-geocoder is a geocoder control for Mapbox GL JS, it's intended to provide a the user interface, that is, an input search box for searching on top of the Mapbox Geocoding API.

If you already have your query and just want to display that location on the map you're better to use the Mapbox JavaScript SDK with geocodeForward, see https://github.com/mapbox/mapbox-sdk-js#installation.

The Console.Log was very helpful, I found out that the data.features.center returns the coordinates which was all what i needed . the full code is below

<html>

<head>
  <script src='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.js'></script>
  <link href='https://api.tiles.mapbox.com/mapbox-gl-js/v0.43.0/mapbox-gl.css' rel='stylesheet' />
  <style>
    body {
      margin: 0;
      padding: 0;
    }
    
    #map {
      position: absolute;
      top: 0;
      bottom: 0;
      width: 100%;
    }
  </style>

</head>

<body style="word-wrap:break-word;">
  <div id='map'></div>
  <script src='https://unpkg.com/mapbox@1.0.0-beta9/dist/mapbox-sdk.min.js'></script>

  <script>
    mapboxgl.accessToken = 'pk.eyJ1IjoibGF3aXgxMCIsImEiOiJjamJlOGE1bmcyZ2V5MzNtcmlyaWRzcDZlIn0.ZRQ73zzVxwcADIPvsqB6mg';
    console.log(mapboxgl.accessToken);
    var client = new MapboxClient(mapboxgl.accessToken);
    console.log(client);

    var address = 't5h 0k7'
    var test = client.geocodeForward(address, function(err, data, res) {
      // data is the geocoding result as parsed JSON
      // res is the http response, including: status, headers and entity properties

      console.log(res);
      console.log(res.url);
      console.log(data);

      var coordinates = data.features[0].center;

      var map = new mapboxgl.Map({
        container: 'map',
        style: 'mapbox://styles/mapbox/streets-v10',
        center: coordinates,
        zoom: 14
      });
      new mapboxgl.Marker()
        .setLngLat(coordinates)
        .addTo(map);


    });
  </script>

</body>

</html>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!