I have a Mapbox GL JS app, where over a map I display some widgets. To make sure nothing on the map will be hidden by them I've added some padding using map.setPadding(). It's an asymmetric one (left is larger than right in my case). It works as intended for things like fitBounds and animation but I also need to set up maxBounds of the map so the user won't pan out of the desired viewport. Unfortunately that doesn't work well with custom padding. When I draw the bounds and use showPadding I can see that those lines won't align. The problem grows bigger the bigger I make the difference between the paddings.
I was wondering if anybody had similar issues or can lead me to a solution where I can have map clamped to some bounds while still being able to use custom padding like I described above.
Here's an example of the issue: https://jsfiddle.net/1ysrgkcL/45/ Notice how the thick black rectangle doesn't align with the padding lines.
I ran into same problem earlier and i fix it using:
fitBounds as it add's the amount of padding(in pixels) to the given bounds.
requestAnimationFrame: In its callback i received the getBounds and set it as max bounds(trick)
Updated code snippet:
<script>
mapboxgl.accessToken = 'pk.eyJ1IjoiYnBhY2h1Y2EiLCJhIjoiY2lxbGNwaXdmMDAweGZxbmg5OGx2YWo5aSJ9.zda7KLJF3TH84UU6OhW16w';
const map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v9',
center: [-73.9774108244587, 40.820698485268366],
zoom: 11.6
});
map.on('load', function () {
const padding = { left: 300, right: 100, top: 100, bottom: 30 }; //<--- padding
const bounds = {
"n": 40.896790957065434,
"s": 40.76021859203365,
"e": -73.85756962495667,
"w": -74.09102645202957
}
const maxBounds = [[bounds.w, bounds.s], [bounds.e, bounds.n]];
//<---- notice here--->
map.fitBounds(maxBounds, {
padding, //<--- used here
linear: true,
duration: 0
});
map.showPadding = true
//<---- notice here--->
requestAnimationFrame(() => {
const getBoundsFromViewport = map.getBounds();
map.setMaxBounds(getBoundsFromViewport);
});
const boundsRect = [
[bounds.e, bounds.n],
[bounds.w, bounds.n],
[bounds.w, bounds.s],
[bounds.e, bounds.s],
[bounds.e, bounds.n]
]
map.on('click', (e) => console.log('##', e.lngLat.toArray()))
map.addLayer({
'id': 'bounds',
'type': 'line',
'source': {
'type': 'geojson',
'data': {
'type': 'Feature',
'geometry': {
'type': 'LineString',
'coordinates': boundsRect
}
}
},
'paint': {
'line-color': '#000000',
'line-width': 10
},
'layout': {}
});
});
</script>
And it will like charm in your case too. Attaching screenshot:
Give it a try!
Related
I have implemented a client-side join from a GitHub based CSV to a Mapbox tileset using a Papa-parse promise function, similar to how it is implemented in: Data Joins : Mapbox JS.
The promise is fulfilled and the data is stored correctly, the outlines of the regions I am trying to visualise show, but there is an issue with data-driven styling with the "interpolate", ['linear'] parameters I am trying to use, from my past experience. The 'accessibilityOutline' ID layer shows its data correctly, so it is confusing to why this is happening.
An error keeps coming up declaring
"Input/output pairs for "interpolate" expressions must be defined using literal numeric values (not computed expressions) for the input values."
I am wondering if anyone else has had this problem, and the way it was overcome. Any help would be grateful.
The code implemented is below, this is all based off the link above. The data is read in correctly and through debug testing I can see that all the data is in the correct format as the
dynamicTyping: true,
is present in the Papa.parse function. However, mapbox looks like it is unable to read this data.
function papaPromise(url) {
return new Promise(function(resolve,reject) {
Papa.parse(url, {
download: true,
header: true,
skipEmptyLines: true,
complete: resolve,
dynamicTyping: true,
});
});
}
const accessibilityCSV = papaPromise("some random url of data");
const mapContainer = useRef();
useEffect(() => {
const map = new mapboxgl.Map({
container: mapContainer.current,
style: "mapbox://styles/mapbox/outdoors-v11",
center: [-2.597, 53.39],
zoom: 9.5,
});
map.on("load", () => {
accessibilityCSV.then(function (results) {
console.log(results.data);
results.data.forEach((row) => {
map.setFeatureState({
source: 'lsoa_ultra_generalised-3gznbd',
sourceLayer: 'lsoa_ultra_generalised-3gznbd',
id: row.lsoa_code
}, {
lsoa_name: row.lsoa_name,
Total_LSOA_population: row.Total_LSOA_population,
LSOA_population_low_income: row.LSOA_population_low_income,
airport_jt60: row.airport_jt60,
airport_jt90: row.airport_jt90,
seaport_jt60: row.seaport_jt60,
seaport_jt90: row.seaport_jt90,
city_jt60: row.city_jt60,
city_jt90: row.city_jt90,
visitor_attraction_jt60: row.visitor_attraction_jt60,
visitor_attraction_jt90: row.visitor_attraction_jt90,
beach_jt60: row.beach_jt60,
beach_jt90: row.beach_jt90,
national_park_jt60: row.national_park_jt60,
national_park_jt90: row.national_park_jt90,
biz_60: row.biz_60,
biz_90: row.biz_90,
NPIER_60: row.nPIER_60,
NPIER_90: row.nPIER_90,
uni_places_60: row.uni_places_60,
uni_places_90: row.uni_places_90
},
);
});
});
map.addSource('northOutline', {
type: "vector",
url: "vectorURL"
})
map.addSource("accessibilitySource", {
type: "vector",
url: "vectorURL",
promoteId: 'LSOA11CD'
});
map.addLayer({
id: 'accessibility',
type: 'fill',
source: 'accessibilitySource',
'source-layer': 'lsoa_ultra_generalised-3gznbd',
paint: {
"fill-color":[
"interpolate",
['linear'],
['number', ["feature-state","Total_LSOA_population"]],
0,
"#fee5d9",
2075,
"#fcae91",
4150,
"#fb6a4a",
6225,
"#de2d26",
8300,
"#a50f15",
/* other */, "#ccc",
],
},
});
map.addLayer({
id:'accessibilityOutline',
type:'line',
source: 'accessibilitySource',
'source-layer': 'lsoa_ultra_generalised-3gznbd',
paint: {
"line-color": '#000000'
},
});
I'm using cytoscape to dynamically create a network visualisation and I'm having trouble to setup the layout correctly.
Occasionally, a collection of nodes is created and attached to a parent node.
Then I call the following function to layout the new nodes and center the graph on that parent:
static DoLayout(node) {
setTimeout(() => {
cy.layout({
name: 'cose',
fit: false,
nodeRepulsion: function (node) { return 99999; },
componentSpacing: 100,
padding: 100,
randomize: false,
animate: 'end',
animationEasing: 'ease-in-out',
animationDuration: 350,
stop: () => {
setTimeout(() => {
cy.zoom(.8)
cy.center(node);
}, 100);
}
})
.run();
}, 50);
}
And here's the issue:
Is there a possibility to have these three actions layout, center and zoom happen at the same time? Or smoothly?
Edit: (fit: true,)
Setting fit to true, as suggested by canbax, solves the 'flickering' issue shown in the gif. However it still doesn't produce a smooth transition (animation?) when zooming and centering. Plus, I don't want the graph to be completely zoomed-out then zoomed-in and centered.
The markers will be added dynamically using firebase.
map.loadImage(
AddressIcon,
function(error, image) {
if (error) throw error;
map.addImage(id + 'address', image);
map.addSource(id + 'point', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
features
]
}
});
map.addLayer({
'id': id + "addresses-layer",
'type': 'symbol',
'source': id + 'point',
'layout': {
'icon-image': id + 'address',
'icon-size': 1
}
});
});
draw = new MapboxDraw({
displayControlsDefault: false,
userProperties: true,
controls: {
polygon: true,
trash: true
},
});
map.addControl(draw, 'bottom-left');
map.addControl(new mapboxgl.NavigationControl());
map.addControl(new mapboxgl.FullscreenControl());
map.on('draw.create', updateDrawArea);
map.on('draw.delete', updateDrawArea);
map.on('draw.update', updateDrawArea);
const updateDrawArea = (e) => {
var data = draw.getAll();
console.log(data);
}
I have the polygon drawing system on the map. I need to get all of the added layers/markers after draw the polygon around the markers. I need to do this using mapbox-gl-js if possible. If not is there any alternatives?
Yes, it is possible through Turf.js.
Turf.js exposes functions such as pointsWithinPolygon, that allow us to specify marker points and polygon coordinates, and returns a list of markers that inside the specified polygon.
For example:
var pointsWithinPolygon = require("#turf/points-within-polygon")
const turf = require('#turf/turf');
var points = turf.points([
[-46.6318, -23.5523],
[-46.6246, -23.5325],
[-46.6062, -23.5513],
[-46.663, -23.554],
[-46.643, -23.557]
]);
var searchWithin = turf.polygon([[
[-46.653,-23.543],
[-46.634,-23.5346],
[-46.613,-23.543],
[-46.614,-23.559],
[-46.631,-23.567],
[-46.653,-23.560],
[-46.653,-23.543]
]]);
var ptsWithin = turf.pointsWithinPolygon(points, searchWithin);
console.log(ptsWithin)
You can refer to this tutorial that explains how we can use turf.js along-side mapbox-gl-draw.
I am building a map with multiple geojsons in Leaflet and it has worked well on a normal size computer screen. It doesn't however work on smaller screens or Apple products and so I am attemting to move my code over to Smap-responsive https://github.com/getsmap/smap-responsive .
I have added a geojson following the given example and styled it based upon attributes, it looks how I want it to and the pop ups work how I want them to. The problem comes when I try to add a second geojson. When I click points on the first layer it works as it should but when I turn off that layer and turn on the second layer the popups don’t work on the second layer. If I refresh the page and try the second layer first, those popups work but then they don’t work on the first layer. The error i get is:
“Uncaught TypeError: Cannot read property 'properties' of undefined”
Here is the code:
var config = {
// These params are default and can be overridden by calling the map with e.g. http://mymap?center=13.1,55.6&zoom=17
params: {
// The map's centering from start. Coordinates should be in WGS 84 and given like [easting, northing] i.e. [longitude, latitude]
center: [14.0, 55.52],
// The initial zoom of the map, In this example I zoom out slightly if the screen is smaller than given number of pixels
zoom: $(window).width() < 600 ? 11 : 11
},
// Optional configuration object for the Leaflet map object. You can use all options specified here: http://leafletjs.com/reference.html#map-class
// mapConfig: {
// maxBounds: [ // Optional. Limit panning of the map. Given as [[north, west], [south, east]]
// [55.71628170645908, 12.6507568359375],
// [55.42589636057864, 13.34564208984375]
// ],
// minZoom: 11, // Optional. Limit how much you can zoom out. 0 is maximum zoomed out.
// maxZoom: 18 // Optional. Limit how much you can zoom in. 18 is usually the maximum zoom.
// },
smapOptions: {
// The text of the <title>-tag
title: "webbkartan",
// The favicon to be used
favIcon: "//assets-cdn.github.com/favicon.ico"
},
// -- Baselayers (background layers) --
bl: [
// -- An openstreetmap layer. Note that all layer types used as overlays can also be used as baselayers, and vice versa (see more layers below). --
{
init: "L.TileLayer",
url: '//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
options: {
layerId: "osm",
displayName: "OSM",
attribution: '<span>© OpenStreetMap contributors</span> | <span>Tiles Courtesy of MapQuest <img src="//developer.mapquest.com/content/osm/mq_logo.png"></span>',
maxZoom: 18
}
}
],
// -- Overlays --
ol: [
{
init: "L.GeoJSON.WFS",
url: document.URL.search(/dev.html?/) > 0 ? "examples/data/recipient.geojson" : "../examples/data/recipient.geojson",
options: {
displayName: "Totalkväve halt",
category: ["Status"],
layerId: "kvave",
attribution: "",
inputCrs: "EPSG:4326",
uniqueKey: "Nr",
selectable: true,
reverseAxis: false,
reverseAxisBbox: true,
geomType: "POINT",
legend:"examples/data/legend/kvave_legend.jpg",
popup:
'<h4>Punkt ${Nr} </h4>'+
'<br><img src="examples/data/diagram/' + '${Ar_kvav}' + '"/ width=400>'+
'<img src="examples/data/diagram/' + '${Man_kvav}' + '"/ width=400>'+
'<p><font size=2>'+ '${Plats}'+
'<br><b> Frekvens: </b>${frekvens_g}/år'+
'<br><b> Senast provtagning: </b> ${sist_anv}'+
'<br><b> Nuvarande status: </b> ${Status_fos} status'+
'<br><b> Senaste uppdaterad: </b> ${uppdaterad}</p>',
style:function(feature){
switch (feature.properties.Status_kva){
case "Extremt hög halt" : return {color: '#FF000D'};
case "Mycket hög halt": return {color: '#FFBB00'};
case null: return {color: '#8C8C89'};
};
}
}
},
{
init: "L.GeoJSON.WFS",
url: document.URL.search(/dev.html?/) > 0 ? "examples/data/recipient.geojson" : "../examples/data/recipient.geojson",
options: {
displayName: "Totalfosfor status",
category: ["Status"],
layerId: "fosfor",
attribution: "",
inputCrs: "EPSG:4326",
uniqueKey: "OBJECTID",
selectable: true,
reverseAxis: false,
reverseAxisBbox: true,
geomType: "POINT",
legend:"examples/data/legend/fos_legend.jpg",
popup:
'<h4>Punkt ${Nr} </h4>'+
'<br><img src="examples/data/diagram/' + '${Ar_fos}' + '"/ width=400>'+
'<img src="examples/data/diagram/' + '${Man_fos}' + '"/ width=400>'+
'<p><font size=2>'+ '${Plats}'+
'<br><b> Frekvens: </b>${frekvens_g}/år'+
'<br><b> Senast provtagning: </b> ${sist_anv}'+
'<br><b> Nuvarande status: </b> ${Status_fos} status'+
'<br><b> Senaste uppdaterad: </b> ${uppdaterad}</p>',
style:function(feature){
switch (feature.properties.Status_fos){
case "Hög" : return {color:'#02A0F5', fillColor: '#02A0F5', fillOpacity:1};
case "God" : return {color:'#29D637', fillColor: '#29D637', fillOpacity:1};
case "Otillfredsställande" : return {color: '#F5AA07', fillColor: '#F5AA07', fillOpacity:1};
case "Dålig": return {color:'#FC0000', fillColor: '#FC0000', fillOpacity:1};
case null: return {color:'#8C8C89', fillColor: '#8C8C89',fillOpacity:1 };
};
}
}
},
],
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Plugins are Leaflet controls. The options of a control
// given here, will override the options in the control.
// Thereby, you can manage everything the control lets
// you manage from this config file – without having to
// edit the plugin itself.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
plugins: [
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Scale is Leaflet's in-built scale bar control. See options: http://leafletjs.com/reference.html#control-scale
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.Scale",
options: {
imperial: false
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// LayerSwitcher is a responsive layer menu for both overlays and baselayers.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.LayerSwitcher",
options: {
toggleSubLayersOnClick: false, // If true, all layers below this header will be turned on when expanding it.
unfoldOnClick: true, // If true, clicking anywhere on a header will unfold it. If false, user has to click on the icon next the header text.
unfoldAll: false, // If true, all subheaders will be unfolded when unfolding a header.
olFirst: false, // If true, the overlays panel is shown at the top
pxDesktop: 992, // Breakpoint for switching between mobile and desktop switcher
btnHide: true, // Show a hide button at the top header
catIconClass: "fa fa-chevron-right" // Icon class for foldable headers
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Zoombar creates a custom zoombar with [+] and [-] buttons.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.Zoombar",
options: {}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Geolocate shows the users position. Based on the HTML5 geolocation API.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.Geolocate",
options: {
position: 'bottomright', // Button's position
locateOptions: {
maxZoom: 17, // Maximum auto-zoom after finding location
enableHighAccuracy: true // true: Will turn on GPS if installed (better accuracy but uses more battery)
}
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// SelectVector is needed to make WMS layers selectable
// using getfeatureinfo requests.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.SelectWMS",
options: {
wmsVersion: "1.3.0", // The WMS version to use in the getfeatureinfo request
info_format: "text/plain", // The fallback info format to fetch from the WMS service. Overridden by layer's info_format in layer's selectOptions.
maxFeatures: 20, // Max features to fetch on click
buffer: 12, // Buffer around click (a larger number makes it easier to click on lines and points)
useProxy: false // If you want call the URL with a prepended proxy URL (defined in ws above)
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// SelectVector is needed in order to make vector (e.g. WFS) layers selectable.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.SelectVector",
options: {
// The select style.
selectStyle: {
weight: 5,
color: '#00FFFF',
fillColor: '#00FFFF',
opacity: 1,
fillOpacity: .5
}
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Search connects to a autocomplete and geolocate service and places a marker
// at the geolocated location.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.Search",
options: {
_lang: {
// Watermark/placeholder for text entry. Language dependent.
"en": {search: "Search address or place"}, // english
"sv": {search: "Sök adress eller plats"} // swedish
},
gui: true, // If false, entry is not shown but the plugin can still take the POI URL parameter
whitespace: "%20", // How to encode whitespace.
wsOrgProj: "EPSG:3008", // The projection of the returned coordinates from the web service
useProxy: false, // If you want call the URL with a prepended proxy URL (defined in ws above)
wsAcUrl: "//kartor.malmo.se/api/v1/addresses/autocomplete/", // Required. Autocomplete service.
wsLocateUrl: "//kartor.malmo.se/api/v1/addresses/geolocate/", // Required. Geolocate service.
acOptions: { // typeahead options (Bootstrap's autocomplete library)
items: 100 // Number of options to display on autocomplete
}
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Print creates a downloadable image server-side. Requires Geoserver and the plugin "Mapfish print".
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// {
// init: "L.Control.Print",
// options: {
// printUrl: "//kartor.malmo.se/print-servlet/leaflet_print/", // The print service URL
// position: "topright" // Button's position
// }
// },
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// ShareLink adds a button which, on click, will create a
// URL which recreates the map, more or less how it looked like.
// It is up to other plugins to add and receive URL parameters by
// listening to the events:
// - Create params: "smap.core.createparams"
// - Apply params: "smap.core.beforeapplyparams" or "smap.core.applyparams"
// For instance:
//
// smap.event.on("smap.core.createparams", function(e, paramsObject) {
// paramsObject.myparameter = 3;
// });
// smap.event.on("smap.core.applyparams", function(e, paramsObject) {
// alert(paramsObject.myparameter);
// });
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.ShareLink",
options: {
position: "topright",
root: location.protocol + "//malmo.se/karta?" // location.protocol + "//kartor.malmo.se/init/?appid=stadsatlas-v1&" // Link to malmo.se instead of directly to map
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// RedirectClick opens a new browser tab when the user clicks on the map.
// The easting ${x} and northing ${y} is sent along to the url. See example below.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init : "L.Control.RedirectClick", // Pictometry
options: {
position: "topright", // Button's position
url: "http://kartor.malmo.se/urbex/index.htm?p=true&xy=${x};${y}", // Malmö pictometry
btnClass: "fa fa-plane", // Button's icon class
cursor: "crosshair" // Cursor shown in map before click
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Info simply creates a toggleable Bootstrap modal which you can fill with any info below.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.Info",
options: {
addToMenu: false, // Create toggle button or not
position: "topright", // Button's position (requires addToMenu == true)
autoActivate: false, // Open from start
// Here follows the content of the modal – language dependent!
_lang: {
"en": {
titleInfo: "<h4>A header</h4>",
bodyContent:
'<p>Some content</p>'
},
"sv": {
titleInfo: "<h4>En rubrik</h4>",
bodyContent:
'<p>Lite innehåll</p>'
}
}
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// MeasureDraw is a combined measure and drawing tool. The created
// markers, lines or polygons can be shared with others
// (geometries and attributes sent along as a URL parameter).
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.MeasureDraw",
options: {
position: "topright", // Button's position
saveMode: "url", // So far url is the only option
layerName: "measurelayer", // The internal layerId for the draw layer
stylePolygon: { // Draw style for polygons
color: '#0077e2',
weight: 3
},
stylePolyline: { // Draw style for polylines
color: '#0077e2',
weight: 9
}
}
},
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// ToolHandler takes care of making all buttons inside the top-right div responsive.
// When the screen width is smaller than the defined breakpoint, the buttons are contained
// within a Bootstrap popover which can be toggled by a single button.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
{
init: "L.Control.ToolHandler",
options: {
showPopoverTitle: false // Show title (header) in the popover
}
}
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// Add2HomeScreen creates a popover on iOS devices supporting
// "Add To Homescreen", which advices the user to add the website
// to the homescreen, making it look almost like a native app.
// <><><><><><><><><><><><><><><><><><><><><><><><><><>
// {
// init: "L.Control.Add2HomeScreen",
// options: {}
// }
]
};
The error points to "feature.properties." in the function that sets the colors of the first layer I turn on and it comes when I click to get a pop up on the second layer I have turned on. I haven't had this problem when using Leaflet without smap-resonsive.
I have tried moving the function out to an external js. file, defining the functions with "var something =". I have tried calling the colors direct from an attribute also but all give the same error.
I am new to Leaflet and Javascript, any help appreciated!
The error was caused by bug which meant that only the uppermost layer was selectable. Described here:
https://github.com/getsmap/smap-responsive/issues/198
Thanks to Johan Lahti for a quick reposonse in solving the problem!
I am trying to append the value of map and values inside this test variable using a jQuery function ( which is at the end). How do I do this?
I want to change the value of map: 'ecoMap' to map: developmentRegionMap and values: Chherti to values: testvalue
function Eco_regions() {
test = $('#world-map').vectorMap({
map: 'ecoMap',
backgroundColor: '#FFFFFF',
regionsSelectable: false,
series: {
regions: [{
values: Chhetri,
scale: ['#fffad6', '#d05300'],
normalizeFunction: 'polynomial'
}]
}
});
};
This is the jquery function which is supposed to append the variable.
$('#change_ecoregions').click(function (e) {
e.preventDefault();
test.map.setValue('developmentRegionMap');
test.series.regions[0].setValues(testvalue);
Eco_regions();
});
What you require is plugin-specific; supposing you're using the jQuery Vector Maps plugin, according to the documentation, you'd have to do this in order to change values after the creation (untested):
jQuery('#vmap').vectorMap('set', 'map', 'developmentRegionMap');
I want to change the value of map: 'ecoMap' to map: developmentRegionMap and values: Chherti to values: testvalue
Then just make them parameters of that function:
function Eco_regions(map, value) {
test = $('#world-map').vectorMap({
map: map || 'ecoMap',
backgroundColor: '#FFFFFF',
regionsSelectable: false,
series: {
regions: [{
values: value || Chhetri,
scale: ['#fffad6', '#d05300'],
normalizeFunction: 'polynomial'
}]
}
});
};
$('#change_ecoregions').click(function (e) {
e.preventDefault();
Eco_regions('developmentRegionMap', testvalue);
});
I couldn't find a great way to just change the variable and have it redraw the map. I think you might need to just blow the old map away and append a new one in.
Define an element for the map
var mapElement = '<div id="world_map" style="width:600px; height: 400px;">';
Create a container div
<div id="container"></div>
When the change event is fired, remove the old map, append a new element to the container, and call the vectorMap function with the new settings.
$('#world_map').remove();
$('#container').append(mapElement);
$('#world_map').vectorMap(options);
Here is a fiddle as an example.
You're calling a function setValues where, unless you've omitted some code, you haven't defined it. If you change it to test.series.regions[0].values = testvalue; you should have better luck. Also, without quotes, testvalue is undefined (unless it's global somewhere) so you'll either need to assign that variable some value or else surround it with quotes to make it a string.
I think it's best to rearrange your function slightly so you can easily adjust the properties:
var test= {
map: 'ecoMap',
backgroundColor: '#FFFFFF',
regionsSelectable: false,
series: {
regions: [{
values: Chhetri,
scale: ['#fffad6', '#d05300'],
normalizeFunction: 'polynomial'
}]
}
};
function Eco_regions(settings) {
$('#world-map').vectorMap(settings);
};
$('#change_ecoregions').click(function (e) {
e.preventDefault();
test.map = 'developmentRegionMap';
test.series.regions[0] = testvalue;
Eco_regions(test);
});