问题
How do I display location of an address on an HTML page using MapBox SDk forward Geo-Coding function. The SDK already does the query, but I need to be able to display the map and its location with a point on the html. here is my sample code.
<html>
<head>
<meta charset="utf-8">
<title>MapBox</title>
<meta name="viewport" content="initial-scale=1,maximum-scale=1,user-scalable=no">
<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;">
<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 = '6 Antares Drive, Ottawa, Ontario, K2E 6AE, Canada'
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);
console.log(err);
});
console.log(test);
// how do I display the address on the HTML?
</script>
</body>
</html>
console.log(res.url) gives me the desired url but how do I display the map and add a marker to it.
回答1:
You need to make a <div> tag that will hold your map. See here for an example
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8' />
<title>Display a map</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<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>
<div id='map'></div> // this is the line you're looking for
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoibGF3aXgxMCIsImEiOiJjamJlOGE1bmcyZ2V5MzNtcmlyaWRzcDZlIn0.ZRQ73zzVxwcADIPvsqB6mg';
var map = new mapboxgl.Map({
container: 'map', // id of the div you assigned above
style: 'mapbox://styles/mapbox/streets-v9', // stylesheet of basemap you want
center: [-74.50, 40], // starting position [lng, lat]
zoom: 9 // starting zoom
});
</script>
</body>
</html>
来源:https://stackoverflow.com/questions/48066274/display-location-with-mapbox-java-script-sdk