【发布时间】:2016-04-14 05:07:11
【问题描述】:
我目前正在使用 Mapbox API 来检索用户在表单中输入的位置。我还使用了 leaflet-angular-directive,它允许我使用附加到我的“$scope”的属性来渲染我的地图。
虽然我可以在用户提交后检索位置并将图钉发布到我的地图上,但我不知道如何自动完成类似于此示例的搜索结果。
这是来自我的控制器的 sn-p。我的 API 端点中的 &autocomplete=true 不起作用。
function CreateController ($http, $scope) {
var vm = this;
vm.new_location = {};
vm.locations = [];
vm.submitLocationForm = function(){
vm.geocode(vm.addPin);
}
//GET LOCATION FROM QUERY
vm.geocode = function(addMapData) {
//api from mapbox with access token
var apiEndpoint = 'https://api.mapbox.com/geocoding/v5/mapbox.places/'+vm.new_location.locationName+'.json?access_token=' + MY_API_KEY + '&autocomplete=true'
//ajax call to get location data from the zipcode
$http.get(apiEndpoint)
.then(function(mapData) {
var coordinates = mapData.data.features[0].center; //array [long, lat]
addMapData(coordinates);// callback function that is called only after http call is receives data
})
}
angular.extend($scope, {
center: {
autoDiscover: true
},
markers: {
}, //markers is empty b/c users will add markers
defaults: {
// minZoom: 2,
// doubleClickZoom: true,
markerZoomAnimation: true
}
);
//adding pin
vm.addPin = function(coordinates){
vm.pinCounter += 1;
vm.new_location.pinOrder = vm.pinCounter;
vm.new_location.longitude = coordinates[0];
vm.new_location.latitude = coordinates[1];
$scope.markers[vm.pinCounter] = {
lat: vm.new_location.latitude,
lng: vm.new_location.longitude,
message: vm.new_location.textContent,
draggable: false,
focus: true,
riseOnHover: true,
zoom: 10
}
}
这是表单的 HTML:
<form ng-submit="CreateController.submitLocationForm()">
<div class="form-group">
<input type="text" ng-model="CreateController.new_location.locationName" class="form-control" placeholder="Location name" autofocus>
</div>
<input type="submit" value="Submit" class="btn btn-block btn-info">
</form>
这是the code that's available on the Mapbox documentation,但我不确定如何修改它以便在 Angular 中使用它:
<html>
<head>
<meta charset=utf-8 />
<title>Geocoding with autocomplete</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v2.4.0/mapbox.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>
<script>
L.mapbox.accessToken = '<your access token here>';
L.mapbox.map('map', 'mapbox.streets')
.addControl(L.mapbox.geocoderControl('mapbox.places', {
autocomplete: true
}));
</script>
</body>
</html>
【问题讨论】:
-
我找到了解决这个问题的方法。我使用angular-js.in/vsgoogleautocomplete 来完成此操作,但似乎使用 Mapbox 应该可以做到这一点。
标签: javascript angularjs autocomplete leaflet mapbox