Mapbox Geolocation, how to load into map? - javascript

I have being playing around with MapBox and I am having some issues with getting the GeoLocation API to send data back to the map and update the it.
This is what I got right now:
mapboxgl.accessToken = 'TOKEN-HERE';
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/streets-v9',
center: [-0.968539, 54.562917],
zoom: 9
});
map.on('style.load', function() {
map.addSource("myMap", {
"type": "geojson",
"data": "https://api.mapbox.com/geocoding/v5/mapbox.places/UK_ADDRESS_HERE.json?country=gb&types=address&autocomplete=true&access_token=TOEKN"
});
map.addLayer({
'id': 'test1',
'type': 'line',
'source': 'myMap',
'interactive': true
});
});

The answer may lie with how you are encoding UK_ADDRESS_HERE.
https://api.mapbox.com/geocoding/v5/mapbox.places/UK_ADDRESS_HERE.json
The request format for the Mapbox Geocding API requires that since the {query} parameter can contain any value, it should be URL-encoded.
That means that a simple geocode request like 10 Downing Street, Westminster must be encoded using encodeURIComponent to 10%20Downing%20Street%2C%20Westminster.
Try this and verify that your request is proper.
curl https://api.tiles.mapbox.com/geocoding/v5/mapbox.places/10%20Downing%20Street%2C%20London.json?access_token=${MAPBOX_ACCESS_TOKEN}

Related

Can't add a geoJson layer to my Open Layers map

Using Open Layers and leaflet-sidebar-v2, I've added the sidebar to my map, this works. However, I also need to add another layer to my map, this layer will outline each country. I have the coordinates stored in a 'borders.json' file. I'm attempting to use D3.json to to import the border coordinates and then L.geoJson to add the new layer to my map.
I'm currently getting the following error message:
Uncaught TypeError: t.getLayerStatesArray is not a function
Here is the relevant part of my code..
var map = new ol.Map({
target: "map",
layers: [
new ol.layer.Tile({
source: new ol.source.OSM(),
}),
],
view: new ol.View({
center: ol.proj.transform([7, 51.2], "EPSG:4326", "EPSG:3857"),
zoom: 3,
}),
});
var sidebar = new ol.control.Sidebar({
element: "sidebar",
position: "left",
});
map.addControl(sidebar);
d3.json(("borders.json"), function (json){
function style(feature) {
return {
fillColor: "transparent",
weight: 1,
opacity: 0.4,
color: 'grey',
fillOpacity: 0.3
}
}
geojson = L.geoJson(json, {
style: style,
}).addTo(map);
})
I think I might be adding the geojson layer to my map incorrectly, but I can't figure out what is wrong. I've spent quite a bit of time playing with it, but no luck.
Any helps is appreciated.
Cheers,
Beat
It might be hard to tell what the problem is without knowing other possible relevant parts of your code. I'd start by checking that the contents of borders.json follows valid GeoJSON format.
This is likely unrelated to your question, but is there a reason that you've declared style as a function like function style(feature) { ... }?
It looks like the style attribute of L.geoJson accepts an object rather than a function.

Filtering through Mapbox points with Mapbox GL JS by properties

I currently have Mapbox running on my site, data points and popups are function while using a dataset uploaded to Mapbox Studio. For the life of me, I cannot filter the points by properties in Javascript (within my html file script tag). I tried setFilter() examples and nothing seems to work.
By the way, I censored our access token and styles url. All of that is working on my end.
mapboxgl.accessToken = 'pk........';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/........',
center: [-111.9671707, 33.30527115],
zoom: 15
});
map.on('click', (event) => {
const features = map.queryRenderedFeatures(event.point, {
layers: ['crime-data-complete (1)']
});
if (!features.length) {
return;
}
const feature = features[0];
const popup = new mapboxgl.Popup({ offset: [0, -15] })
.setLngLat(feature.geometry.coordinates)
.setHTML(
`<h2 style="text-transform: capitalize;">${feature.properties.Crime}</h2><p><strong>Date: </strong>${feature.properties.Date}</p><p><strong>Address: </strong>${feature.properties.Address}</p><p><strong>City: </strong>${feature.properties.City}</p><p><strong>State: </strong>${feature.properties.State}</p>`
)
.addTo(map);
});
map.setFilter('crime-data-complete (1)', ['all', ['==', 'Crime', 'Theft']]);
If you are using the ['all', ...] then you should include a get for the properties.
In your case that would be:
map.setFilter('crime-data-complete (1)', ['all', ['==', ['get', 'Crime'], 'Theft']]);
If you're using one filter only, you can drop the ['all', ...] and use this instead:
map.setFilter('crime-data-complete (1)', ['==', 'Crime', 'Theft']);

Google Maps API limits with Fusion Tables

I was interested in using google maps API with quite big KML imported as fusion table. I used the basic example from google tutorials on how to use fusion table as a layer in a map, and after ~8 hours of me just trying out stuff the API started to throw an error, that 25.000 map loads limit have been reached. Google developer console doesn't say it's even close hitting any limit. Does anybody know if KML complexity or size can affect API limits? Or maybe I've some potential loops in the code? Or generally what could cause the problem? Here is what I did:
<script type="text/javascript">
function initialize() {
console.log('asdf');
var mapDiv = document.getElementById('googft-mapCanvas');
var map = new google.maps.Map(mapDiv, {
center: new google.maps.LatLng(51.11786991747952, 17.001362352071737),
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend-open'));
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(document.getElementById('googft-legend'));
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: {
enabled: false
},
query: {
select: "col13",
from: "<TABLE>",
where: ""
},
options: {
styleId: 2,
templateId: 2
},
styles: [{
where: 'col3 \x3d \x27VALUE\x27',
polygonOptions: {
fillColor: '#0000FF'
}
}]
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Thanks

Leaflet swap the coordinates when use geoJson

I have little Leaflet application where the app get geoJson objects from server, and display it, specially LineString. The JSON parser that i use on server side works properly. And the client side script was ok too.
But some reasons I would like to draw arrow on the routes, and I can't figure out how to do it when using L.geoJson().
Code with L.geoJson():
getJsonFrom(routeQueryURL, params, function(data) {
var a = L.geoJson(data, {
onEachFeature: bindRouteDirection,
}).addTo(map);
});
Because I don't want to change anything on server side, I tried this:
getJsonFrom(routeQueryURL, param, function(data) {
$.each(data, function(index, feature) {
var polyline = new L.Polyline(feature.geometry.coordinates, {
color: feature.properties.color,
opacity: 0.8
}).addTo(routeMapLayer);
var decorator = L.polylineDecorator(polyline, {
patterns: [{
offset: 25,
repeat: 50,
symbol: L.Symbol.arrowHead({
pixelSize: 15,
pathOptions: {
stroke: true,
color: feature.properties.color,
fillOpacity: 0.8,
polygon: false,
weight: 3
}
})
}]
}).addTo(routeMapLayer);
map.addLayer(routeMapLayer);
});
});
So i access the array of coordinates from the geoJson object, and some other data, and draw the polyline directly on to map.The problem is that it's put my route into the middle of middle east instead of Hungary, so it's actually swap the coordinates. Why does L.Polyline handle the different form L.geoJson()?
Use L.GeoJSON.coordsToLatLng() and read why sometimes coordinates are lat-lng and sometimes lng-lat.

UTM and GeoJson in openlayers

I want to implement this example http://api.geoext.org/1.1/examples/feature-grid.html made of geoext and openlayers, that feature grid is populated of a geojson file
In my development I have a geojson file with utm format, this is a single feature of my file (the coordinates are utm)
{"geometry": {"type": "Point", "coordinates": [7535169.36, 402844.172]}, "type": "Feature", "properties": {"NOMBRE": "LA VICTORIA", "CODIGO": "1702"}, "id": "1702"}
I tried to show the points in my code, but I can't see anything, this is my code
// create feature store, binding it to the vector layer
store = new GeoExt.data.FeatureStore({
layer: vecCiudades,
fields: [
{ name: 'NOMBRE' },
{ name: 'CODIGO' }
],
proxy: new GeoExt.data.ProtocolProxy({
protocol: new OpenLayers.Protocol.HTTP({
url: "data/summits.json",
format: new OpenLayers.Format.GeoJSON({
ignoreExtraDims: true,
internalProjection: new OpenLayers.Projection("EPSG:900913"),
externalProjection: new OpenLayers.Projection("EPSG:4326")
})
})
}),
autoLoad: true
});
as you can see, I tried to specify the internal and external projection of the feature store, my implementation looks like the example of the link mentioned above, but when I select a city the map is located to a wrong place (the place is shown near south pole, but it has to be near south america)
Thanks in advance
For what reason FeatureStore..? Just define layer as following:
var vecCiudades = new OpenLayers.Layer.Vector('MyLayer', {
strategies:[new OpenLayers.Strategy.BBOX()],
isBaseLayer:false,
projection:new OpenLayers.Projection("EPSG:900913"),
styleMap:new OpenLayers.StyleMap(null),
transitionEffect:'resize',
protocol:new OpenLayers.Protocol.HTTP({
url: "data/summits.json",
format:new OpenLayers.Format.GeoJSON({
ignoreExtraDims:true
}),
readWithPOST:false,
updateWithPOST:false,
srsInBBOX:true
})
});
Also register following event on map:
map.events.register("moveend", this, function (e) {
vecCiudades.refresh({force:true});
});
That will reread GeoJSON anytime moved or zoomed map and request will contain bounding box of visible area so you can only send features that going to be visible not all of them.

Categories