Initialize mapBox map with dropped marker and search query - mapbox

I have mapbox setup with geocoding so that a user can type in the 'Search' box, and once a location is selected, a marker is dropped at that location. I would like a marker to already be dropped on the map and a search term to already be entered into the Search box at the time of page load (I have a setup where a user selects a location, and if they go back to edit the page I want them to be able to see the location they had previously selected). Is this possible?
My code for initializing is:
initMap(lat, lng) {
const mapboxgl = require('mapbox-gl/dist/mapbox-gl.js')
mapboxgl.accessToken =
'access_token'
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11?optimize=true',
center: [lat, lng],
zoom: 8,
attributionControl: false,
})
const geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
})
map.addControl(geocoder)
map.on('load', () => {
geocoder.on('result', (result) => {
const inputResult = result.result
const coordinates = inputResult.geometry.coordinates
const placeName = inputResult.place_name
const lng = coordinates[0]
const lat = coordinates[1]
this.location = placeName
this.latLng = [lat, lng]
})
})
},

You can specify a query which is already displayed in the search input box and for which a marker is automatically added to the map by using MapboxGeocoder#query in conjunction with Map#on and the 'load' event. For example, the following code displays text in the input field and a marker for "High Park" on map load:
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v11',
center: [-79.4512, 43.6568],
zoom: 13
});
var geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl
});
map.addControl(geocoder);
map.on('load', () => {
geocoder.query('High Park');
});

Related

how to smothly translate/animate updated positions of mapboxgl JS points layer symbols

i'm trying to figure out how to animate the update of this map layer so that points translate smoothly to new positions rather than simply appearing there. i have not found any useful starting points in the mpabox gl tutorials / examples and was wondering if there is a straightforward way to approach this. thanks
the code below fetches a geojson doc from an api once every 60 seconds and updates the map layer.
var map = new mapboxgl.Map({
container: 'map', // container id
style: 'mapbox://styles/mapbox/light-v10', // style URL
center: [-73.93, 40.73], // centroid of NYC
zoom: 11 // starting zoom
});
var url = '/api/v1/nyc/livemap';
map.on('load', function () {
var request = new XMLHttpRequest();
window.setInterval(function () {
// make a GET request to parse the GeoJSON at the url
request.open('GET', url, true);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
// retrieve the JSON from the response
var json = JSON.parse(this.response);
map.getSource('observations').setData(json);
map.flyTo({
center: json.geometry.coordinates,
speed: 0.5
});
}
};
request.send();
}, 60000); // refresh every n milliseconds
map.addSource('observations', { type: 'geojson', data: url });
map.addLayer({
'id': 'buses',
'type': 'circle',
'source': 'observations',
'paint': {
'circle-radius': 3,
//'circle-color': '#0039A6'
'circle-color': [
'match',
['get', 'occupancy'],
'full',
'#e55e5e',
'standingAvailable',
'#FFFF00',
'seatsAvailable',
'#00FF00',
/* null */ '#87CEFA'
]
},
});
});
Mapbox GL JS doesn't contain any mechanism for animating data points from one location to another.
You could use Turf's along function to interpolate each point some proportion along the way from its previous location to its new location.

Setting zoom level after selecting Geocoder result

Is it possible in Mapbox GL to set a zoom level after the user selects one search result? My goal is to show at least a few markers on the map around the user. Or is there another way to achieve the same result, like zoom to geocoder marker + nearest marker?
You can set the zoom level that the Mapbox geocoder goes to when there's a result like this:
new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
zoom: 12
})
After the user selects a geocoder result, its possible to give him some options to fit specific zoom level, by using the flyTo options
var geocoder = new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
mapboxgl: mapboxgl,
flyTo: {
padding: 15, // If you want some minimum space around your result
easing: function(t) {
return t;
},
maxZoom: 6, // If you want your result not to go further than a specific zoom
}
})
More options for the flyTo property here : https://docs.mapbox.com/mapbox-gl-js/api/map/#map#flyto
You want to use the zoom variable from flyTo
map.addControl(
new MapboxGeocoder({
accessToken: mapboxgl.accessToken,
flyTo: {
bearing: 0,
speed: 0.8,
curve: 1,
zoom: 6,
easing: function (t) {
return t;
}
},
mapboxgl: mapboxgl,
})
);

Why some times google map doesn't fit correctly in ionic?

In the following code in Ionic Project, sometimes map doesn't fit correctly an center
code:
initMap() {
this.mapInitialised = true;
this.bounds = new google.maps.LatLngBounds();
this.Geolocation.getCurrentPosition().then((position) => {
this.location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let mapOptions = {
center: this.location,
zoom: 15,
draggable: true,
backgroundColor: 'white',
fullscreenControl: false,
mapTypeControl: false,
zoomControl: true,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
this.map.fitBounds(this.bounds); //# auto - zoom
this.map.panToBounds(this.bounds);
console.log(this.location);
this.PostMarker(this.Postlatlng);
this.CurrentMarker(this.location);
});
}
CurrentMarker(location){
console.log(location.lat, location.lng);
let image = 'https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi_hdpi.png';
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: location,
icon: image
});
this.bounds.extend(new google.maps.LatLng(location.lat(), location.lng()));
}
PostMarker(location) {
console.log(location.lat,location.lng);
let image = 'https://maps.gstatic.com/mapfiles/api-3/images/spotlight-poi_hdpi.png';
let marker = new google.maps.Marker({
map: this.map,
animation: google.maps.Animation.DROP,
position: location,
icon: image
});
this.bounds.extend(new google.maps.LatLng(location.lat, location.lng));
}
output:
after zooming out:
update
As you can see in the output map of the screen is pacific ocean while test data point is a place in Tibet and the second point is my current location in Iran. instead of fitting this two point in screen it shows wrong location/area.
This problem mostly happens when two point is so far from each other. In near location Isaw this problem one or two times.
Set the minZoom map option. Otherwise, the screenshot you have posted it how the API (correctly) behaves when you zoom out to 0.
For example:
new google.maps.Map(element,{minZoom:3});

multiple point direction draw in GL mapbox

I have draw direction to more then 2 park in gl mapbox.
I have try this code but not work perfectly.
mapboxgl.accessToken = 'pk.eyJ1IjoiYWNoYWxwcmFqYXBhdGkiLCJhIjoiY2lyNGkwZGsxMDFpenUybHd5bjRtMjVjeiJ9.2teTa5MmVqOW-MDpryv56w';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/achalprajapati/cis1byfch0008hgnitiwbym9c',
center: [-122.222461, 37.172263],
zoom: 8
});
var directions = new mapboxgl.Directions({
unit: 'metric', // Use the metric system to display distances.
profile: 'walking', // Set the initial profile to walking.
container: 'directions', // Specify an element thats not the map container.
// proximity: [-122.222453, 37.172271] // Give search results closer to these coordinates higher priority.
});
debugger;
//map.addControl(new mapboxgl.Directions());
//map.addControl(directions);
map.on('load', function () {
directions.setOrigin([-122.222461, 37.172263]);
directions.addWaypoint(0, [-122.222461, 37.172263]);
directions.addWaypoint(1, [-122.483318, 37.724502]);
directions.setDestination([-122.483318, 37.724502]);
});
directions.on('route', function (e) {
console.log(e.route); // Logs the current route shown in the interface.
});
there was a breaking change in a recent update of mapbox-gl-js that caused the mapbox-gl-directions plugin to error.
Here is a working jsfiddle of your code with the new versions (v2.2.0 of mapbox-gl-directions plugin and v0.22.1 of mapbox-gl-js)
mapboxgl.accessToken = 'pk.eyJ1IjoiYWNoYWxwcmFqYXBhdGkiLCJhIjoiY2lyNGkwZGsxMDFpenUybHd5bjRtMjVjeiJ9.2teTa5MmVqOW-MDpryv56w';
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/achalprajapati/cis1byfch0008hgnitiwbym9c',
center: [-122.222461, 37.172263],
zoom: 8
});
var directions = new mapboxgl.Directions({
unit: 'metric', // Use the metric system to display distances.
profile: 'walking', // Set the initial profile to walking.
container: 'directions', // Specify an element thats not the map container.
});
map.addControl(directions)
map.on('load', function () {
directions.setOrigin([-122.222461, 37.172263]);
directions.addWaypoint(0, [-122.222461, 37.172263]);
directions.addWaypoint(1, [-122.483318, 37.724502]);
directions.setDestination([-122.483318, 37.724502]);
});
directions.on('route', function (e) {
console.log(e.route); // Logs the current route shown in the interface.
});

Google Map Makers Sprite in OSX not displaying

I can't seem to get the my map markers to display when I use an image sprite on the iphone. They appear when I use the standard google map markers on iphone and when viewing the site in the desktop the sprite icons work fine.
Here is the code I use to create the markers, I am using Zepto but JQuery could as easily apply.
$.ajax({
dataType: 'jsonp',
url: myLocations.LocatorUrl,
timeout: 8000,
success: function(data) {
var infoWindow = new google.maps.InfoWindow();
var bounds = new google.maps.LatLngBounds();
$.each(data, function(index, item){
var data = item, pincolor,
latLng = new google.maps.LatLng(data.lat, data.lng);
var d = 'http://blah';
var pinImage = new google.maps.MarkerImage(d+"/assets/img/sprite.locator.png",
new google.maps.Size(24, 36),
new google.maps.Point(0,25),
new google.maps.Point(10, 34));
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.type,
icon: pinImage
});
bounds.extend(latLng); // Extend the Latlng bound method
var bubbleHtml = '<div class="bubble"><h2>'+item.type+'</h2><p>'+item.address+'</p></div>'; // Custom HTML for the bubble
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(bubbleHtml);
infoWindow.open(map, marker);
});
markers.push(marker); // Push markers into an array so they can be removed
})(marker, data);
});
map.fitBounds(bounds); // Center based on values added to bounds
}, error: function(x, t, m) {
console.log('errors')
if(t==="timeout") {
alert("got timeout");
} else {
alert(t);
}
}
});
Got it. Turns out the images I was referencing were on localhost, when I swapped this to the actual IP address of my local machine it worked.