Legacy
Mapbox.js is no longer in active development. To learn more about our newer mapping tools see Mapbox GL JS.
Point in polygon
Drag a marker to see what state it's in.
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Point in polygon</title>
<meta name='viewport' content='initial-scale=1,maximum-scale=1,user-scalable=no' />
<script src='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.js'></script>
<link href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css' rel='stylesheet' />
<style>
body { margin:0; padding:0; }
#map { position:absolute; top:0; bottom:0; width:100%; }
</style>
</head>
<body>
<style>
.state {
position:absolute;
top:10px;
right:10px;
z-index:1000;
}
.state strong {
background:#404040;
color:#fff;
display:block;
padding:10px;
border-radius:3px;
}
</style>
<!--
This example requires jQuery to load the file with AJAX.
You can use another tool for AJAX.
This pulls the file airports.csv, converts into into GeoJSON by autodetecting
the latitude and longitude columns, and adds it to the map.
Another CSV that you use will also need to contain latitude and longitude
columns, and they must be similarly named.
-->
<script src='https://code.jquery.com/jquery-1.11.0.min.js'></script>
<script src='https://api.mapbox.com/mapbox.js/plugins/leaflet-pip/v0.0.2/leaflet-pip.js'></script>
<div id='map'></div>
<div id='state' class='state'></div>
<script>
L.mapbox.accessToken = '<your access token here>';
var state = document.getElementById('state');
var map = L.mapbox.map('map')
.setView([38, -95], 4)
.addLayer(L.mapbox.styleLayer('mapbox://styles/mapbox/light-v10'));
$.ajax({
url: '/mapbox.js/assets/data/us-states.geojson',
dataType: 'json',
success: function load(d) {
var states = L.geoJson(d).addTo(map);
L.marker([38, -102], {
icon: L.mapbox.marker.icon({
'marker-color': '#f86767'
}),
draggable: true
}).addTo(map)
.on('dragend', function(e) {
var layer = leafletPip.pointInLayer(this.getLatLng(), states, true);
if (layer.length) {
state.innerHTML = '<strong>' + layer[0].feature.properties.name + '</strong>';
} else {
state.innerHTML = '';
}
});
}
});
</script>
Get a free Mapbox account to create your own custom map and use it in this example.
Use this example by copying its source into your own HTML page and
replacing the Map ID
with
one of your own from your projects.
Having trouble with JavaScript? Try out Codecademy
or contact our support team.