Mapbox Map Matching API lets you use snap your GPS traces
to the OpenStreetMap road and path network.

      $ mapbox mapmatching trace.geojson

An access token is required, see `mapbox --help`.
174017
def match(ctx, features, profile, gps_precision):
    
    access_token = (ctx.obj and ctx.obj.get('access_token')) or None

    features = list(features)
    if len(features) != 1:
        raise click.BadParameter(
            "Mapmatching requires a single LineString feature")

    service = mapbox.MapMatcher(access_token=access_token)
    try:
        res = service.match(
            features[0],
            profile=profile,
            gps_precision=gps_precision)
    except mapbox.errors.ValidationError as exc:
        raise click.BadParameter(str(exc))

    if res.status_code == 200:
        stdout = click.open_file('-', 'w')
        click.echo(res.text, file=stdout)
    else:
        raise MapboxCLIException(res.text.strip())
1271754
public static ClientCredentials loadFromMap(Map<String, Object> map) {
        ClientCredentials creds = new ClientCredentials();
        creds.name = (String) map.get("name");
        creds.id = (String) map.get("_id");
        creds.secret = (String) map.get("secret");
        creds.uri = (String) map.get("uri");
        creds.descr = (String) map.get("descr");
        creds.type = ((Integer) map.get("type")).intValue();
        creds.status = ((Integer) map.get("status")).intValue();
        creds.created = (Long) map.get("created");
        creds.scope = (String) map.get("scope");
        if (map.get("applicationDetails") != null) {
            creds.applicationDetails = JsonUtils.convertStringToMap(map.get("applicationDetails").toString());
        }
        return creds;
    }
383408
function findMatch(routes, path) {
      var pathname = PathUtils.withoutQuery(path);
      var query = PathUtils.extractQuery(path);
      var match = null;

      for (var i = 0, len = routes.length; match == null && i < len; ++i) match = deepSearch(routes[i], pathname, query);

      return match;
    }
687773
function ( ) {
			if ( ! options.exist ) {
				// http request to Nominatim to performs the Geocoding of the pin.
				// To avoid to much call to Nominatim with the same position,
				// the call is only performed when it's a new pin
				var NominatimUrl = 
					'http://nominatim.openstreetmap.org/reverse?format=json&lat=' +
					latlng.lat +
					'&lon=' +
					latlng.lng +
					'&zoom=' +
					Map.getZoom ( ) +
					'&addressdetails=1&accept-language=' +
					_Translator.UserLanguage +
					'&osm_type=W';
				var XmlHttpRequest = new XMLHttpRequest ( );
				XmlHttpRequest.onreadystatechange = function ( ) { 
					if ( XmlHttpRequest.readyState == 4 && XmlHttpRequest.status == 200 ) {
						_NominatimCallback ( XmlHttpRequest.responseText );
					}
				};  
				XmlHttpRequest.open ( "GET", NominatimUrl, true );
				XmlHttpRequest.send ( null );
			}
		}
637414
function getVisUrl(url) {
    var match = /https?:\/\/(\S+)\.cartodb\.com\/viz\/(\S+)\/(?:public_)?map/.exec(url);
    if (match) {
        var user = match[1],
            mapId = match[2];
        return 'https://' + user + '.cartodb.com/api/v2/viz/' + mapId + '/viz.json';
    }
}
92329
function getMapPath (dataOpts, opts) {
	var result;

	if (dataOpts.map.annotation) {
		result = path.join(path.dirname(dataOpts.to), dataOpts.map.annotation);
	}
	else {
		result = dataOpts.to +'.map';
	};

	return path.normalize(result);
}
437097
function findRoute(from, to, map, opt) {

        var precision = opt.precision;

        // Get grid for this route.

        var sourceAnchor, targetAnchor;

        if (from instanceof g.Rect) { // `from` is sourceBBox
            sourceAnchor = round(getSourceAnchor(this, opt).clone(), precision);
        } else {
            sourceAnchor = round(from.clone(), precision);
        }

        if (to instanceof g.Rect) { // `to` is targetBBox
            targetAnchor = round(getTargetAnchor(this, opt).clone(), precision);
        } else {
            targetAnchor = round(to.clone(), precision);
        }

        var grid = getGrid(opt.step, sourceAnchor, targetAnchor);

        // Get pathfinding points.

        var start, end; // aligned with grid by definition
        var startPoints, endPoints; // assumed to be aligned with grid already

        // set of points we start pathfinding from
        if (from instanceof g.Rect) { // `from` is sourceBBox
            start = sourceAnchor;
            startPoints = getRectPoints(start, from, opt.startDirections, grid, opt);

        } else {
            start = sourceAnchor;
            startPoints = [start];
        }

        // set of points we want the pathfinding to finish at
        if (to instanceof g.Rect) { // `to` is targetBBox
            end = targetAnchor;
            endPoints = getRectPoints(targetAnchor, to, opt.endDirections, grid, opt);

        } else {
            end = targetAnchor;
            endPoints = [end];
        }

        // take into account only accessible rect points (those not under obstacles)
        startPoints = startPoints.filter(map.isPointAccessible, map);
        endPoints = endPoints.filter(map.isPointAccessible, map);

        // Check that there is an accessible route point on both sides.
        // Otherwise, use fallbackRoute().
        if (startPoints.length > 0 && endPoints.length > 0) {

            // The set of tentative points to be evaluated, initially containing the start points.
            // Rounded to nearest integer for simplicity.
            var openSet = new SortedSet();
            // Keeps reference to actual points for given elements of the open set.
            var points = {};
            // Keeps reference to a point that is immediate predecessor of given element.
            var parents = {};
            // Cost from start to a point along best known path.
            var costs = {};

            for (var i = 0, n = startPoints.length; i < n; i++) {
                // startPoint is assumed to be aligned already
                var startPoint = startPoints[i];

                var key = getKey(startPoint);

                openSet.add(key, estimateCost(startPoint, endPoints));
                points[key] = startPoint;
                costs[key] = 0;
            }

            var previousRouteDirectionAngle = opt.previousDirectionAngle; // undefined for first route
            var isPathBeginning = (previousRouteDirectionAngle === undefined);

            // directions
            var direction, directionChange;
            var directions = opt.directions;
            getGridOffsets(directions, grid, opt);

            var numDirections = directions.length;

            var endPointsKeys = util.toArray(endPoints).reduce(function(res, endPoint) {
                // endPoint is assumed to be aligned already

                var key = getKey(endPoint);
                res.push(key);
                return res;
            }, []);

            // main route finding loop
            var loopsRemaining = opt.maximumLoops;
            while (!openSet.isEmpty() && loopsRemaining > 0) {

                // remove current from the open list
                var currentKey = openSet.pop();
                var currentPoint = points[currentKey];
                var currentParent = parents[currentKey];
                var currentCost = costs[currentKey];

                var isRouteBeginning = (currentParent === undefined); // undefined for route starts
                var isStart = currentPoint.equals(start); // (is source anchor or `from` point) = can leave in any direction

                var previousDirectionAngle;
                if (!isRouteBeginning) previousDirectionAngle = getDirectionAngle(currentParent, currentPoint, numDirections, grid, opt); // a vertex on the route
                else if (!isPathBeginning) previousDirectionAngle = previousRouteDirectionAngle; // beginning of route on the path
                else if (!isStart) previousDirectionAngle = getDirectionAngle(start, currentPoint, numDirections, grid, opt); // beginning of path, start rect point
                else previousDirectionAngle = null; // beginning of path, source anchor or `from` point

                // check if we reached any endpoint
                if (endPointsKeys.indexOf(currentKey) >= 0) {
                    opt.previousDirectionAngle = previousDirectionAngle;
                    return reconstructRoute(parents, points, currentPoint, start, end, grid, opt);
                }

                // go over all possible directions and find neighbors
                for (i = 0; i < numDirections; i++) {
                    direction = directions[i];

                    var directionAngle = direction.angle;
                    directionChange = getDirectionChange(previousDirectionAngle, directionAngle);

                    // if the direction changed rapidly, don't use this point
                    // any direction is allowed for starting points
                    if (!(isPathBeginning && isStart) && directionChange > opt.maxAllowedDirectionChange) continue;

                    var neighborPoint = align(currentPoint.clone().offset(direction.gridOffsetX, direction.gridOffsetY), grid, precision);
                    var neighborKey = getKey(neighborPoint);

                    // Closed points from the openSet were already evaluated.
                    if (openSet.isClose(neighborKey) || !map.isPointAccessible(neighborPoint)) continue;

                    // We can only enter end points at an acceptable angle.
                    if (endPointsKeys.indexOf(neighborKey) >= 0) { // neighbor is an end point

                        var isNeighborEnd = neighborPoint.equals(end); // (is target anchor or `to` point) = can be entered in any direction

                        if (!isNeighborEnd) {
                            var endDirectionAngle = getDirectionAngle(neighborPoint, end, numDirections, grid, opt);
                            var endDirectionChange = getDirectionChange(directionAngle, endDirectionAngle);

                            if (endDirectionChange > opt.maxAllowedDirectionChange) continue;
                        }
                    }

                    // The current direction is ok.

                    var neighborCost = direction.cost;
                    var neighborPenalty = isStart ? 0 : opt.penalties[directionChange]; // no penalties for start point
                    var costFromStart = currentCost + neighborCost + neighborPenalty;

                    if (!openSet.isOpen(neighborKey) || (costFromStart < costs[neighborKey])) {
                        // neighbor point has not been processed yet
                        // or the cost of the path from start is lower than previously calculated

                        points[neighborKey] = neighborPoint;
                        parents[neighborKey] = currentPoint;
                        costs[neighborKey] = costFromStart;
                        openSet.add(neighborKey, costFromStart + estimateCost(neighborPoint, endPoints));
                    }
                }

                loopsRemaining--;
            }
        }

        // no route found (`to` point either wasn't accessible or finding route took
        // way too much calculation)
        return opt.fallbackRoute.call(this, start, end, opt);
    }
238823
private static void asyncMapboxDirectionsRequest() {

    // 1. Pass in all the required information to get a route.
    MapboxDirections request = MapboxDirections.builder()
      .accessToken(BuildConfig.MAPBOX_ACCESS_TOKEN)
      .origin(Point.fromLngLat(-95.6332, 29.7890))
      .destination(Point.fromLngLat(-95.3591, 29.7576))
      .profile(DirectionsCriteria.PROFILE_CYCLING)
      .steps(true)
      .build();

    // 2. Now request the route using a async call
    request.enqueueCall(new Callback<DirectionsResponse>() {
      @Override
      public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
        // 3. Log information from the response
        if (response.isSuccessful()) {
          System.out.printf("%nGet the street name of the first step along the route: %s",
            response.body().routes().get(0).legs().get(0).steps().get(0).name());
        }
      }

      @Override
      public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
        System.err.println(throwable);
      }
    });
  }
1004993
def query_search_api(min_lat, max_lat, min_lon, max_lon, max_results):
    '''
    
    '''

    # Create URL
    params = urllib.urlencode(zip(
        ['client_id', 'bbox', 'per_page'],
        [CLIENT_ID, ','.join([str(min_lon), str(min_lat), str(
            max_lon), str(max_lat)]), str(max_results)]
    ))
    print(MAPILLARY_API_IM_SEARCH_URL + params)

    # Get data from server, then parse JSON
    query = urllib2.urlopen(MAPILLARY_API_IM_SEARCH_URL + params).read()
    query = json.loads(query)['features']

    print("Result: {0} images in area.".format(len(query)))
    return query
1028746
function googleMapsApiLoader(params) {
  if (googleApi) {
    return Promise.resolve(googleApi);
  }

  return new Promise(function(resolve, reject) {
    loadAutoCompleteAPI(params);

    window.googleMapsAutoCompleteAPILoad = function() {
      googleApi = window.google;
      resolve(googleApi);
    };

    setTimeout(function() {
      if (!window.google) {
        reject(new Error('Loading took too long'));
      }
    }, 5000);
  });
}
738567
function doSearch() {
    var value = document.getElementById('search').value;
    marks = [];
    marksIndex = 0;
    for (var key in markers) {
        if ( (~(key.toLowerCase()).indexOf(value.toLowerCase())) && (mb.contains(markers[key].getLatLng()))) {
            marks.push(markers[key]);
        }
        if (markers[key].icon === value) {
            marks.push(markers[key]);
        }
    }
    moveToMarks();
    if (marks.length === 0) {
        // If no markers found let's try a geolookup...
        var protocol = location.protocol;
        if (protocol == "file:") { protocol = "https:"; }
        var searchUrl = protocol + "//nominatim.openstreetmap.org/search?format=json&limit=1&q=";

        fetch(searchUrl + value) // Call the fetch function passing the url of the API as a parameter
        .then(function(resp) { return resp.json(); })
        .then(function(data) {
            if (data.length > 0) {
                var bb = data[0].boundingbox;
                map.fitBounds([ [bb[0],bb[2]], [bb[1],bb[3]] ]);
                map.panTo([data[0].lat, data[0].lon]);
            }
            else {
                document.getElementById('searchResult').innerHTML = "&nbsp;<font color='#ff0'>Not Found</font>";
            }
        })
        .catch(function(err) {
            if (err.toString() === "TypeError: Failed to fetch") {
                document.getElementById('searchResult').innerHTML = "&nbsp;<font color='#ff0'>Not Found</font>";
            }
        });
    }
    else {
        if (lockit) {
            document.getElementById('searchResult').innerHTML = "&nbsp;<font color='#ff0'>Found "+marks.length+" results within bounds.</font>";
        } else {
            document.getElementById('searchResult').innerHTML = "&nbsp;<font color='#ff0'>Found "+marks.length+" results.</font>";
        }
    }
}
1003793
function tileUrlFunction(tileCoord) {
  return ('https://{a-d}.tiles.mapbox.com/v4/mapbox.mapbox-streets-v6/' +
      '{z}/{x}/{y}.vector.pbf?access_token=' + key)
    .replace('{z}', String(tileCoord[0] * 2 - 1))
    .replace('{x}', String(tileCoord[1]))
    .replace('{y}', String(tileCoord[2]))
    .replace('{a-d}', 'abcd'.substr(
      ((tileCoord[1] << tileCoord[0]) + tileCoord[2]) % 4, 1));
}
1159154
def getmap(self, path, query=None):
        
        code, data, ctype = self.get(path, query)
        if ctype != 'application/json':
            self.log.error("Expecting JSON from GET of '%s', got '%s'", self.lastpath, ctype)
            raise HttpError(code=400, content_type='text/plain', content='Remote returned invalid content type: '+ctype)
        try:
            result = json.loads(data)
        except Exception as e:                                                                  # pragma: no cover
            self.log.error("Could not load JSON content from GET %r -- %s", self.lastpath, e)
            raise HttpError(code=400, content_type='text/plain', content='Could not load JSON content')
        return result
492262
function doGeojson(g) {
    console.log("GEOJSON",g);
    if (!basemaps["geojson"]) {
        var opt = { style: function(feature) {
                var st = { stroke:true, color:"#910000", weight:2, fill:true, fillColor:"#910000", fillOpacity:0.3 };
                if (feature.hasOwnProperty("properties")) {
                    console.log("GPROPS", feature.properties)
                }
                if (feature.hasOwnProperty("style")) {
                    console.log("GSTYLE", feature.style)
                }
                return st;
            }
        }
        opt.onEachFeature = function (f,l) {
            if (f.properties) { l.bindPopup('<pre>'+JSON.stringify(f.properties,null,' ').replace(/[\{\}"]/g,'')+'</pre>'); }
        }
        overlays["geojson"] = L.geoJson(g,opt);
        layercontrol.addOverlay(overlays["geojson"],"geojson");
    }
    overlays["geojson"].addData(g);
}
704262
def open_street_map_geoloc_link(data):
    
    if isinstance(data, str):
        lat_lon = ip_geoloc(data)
        if lat_lon is None:
            return ''
        lat, lon = lat_lon
    else:
        lat, lon = data
    return 'https://www.openstreetmap.org/search' \
           '?query=%s%%2C%s#map=7/%s/%s' % (lat, lon, lat, lon)
1161909
public Map<String, Object> snapshotTracingData() {

        Map<String, Object> traceMap = new LinkedHashMap<>();
        traceMap.put("version", 1L);
        traceMap.put("startTime", rfc3339(startRequestTime));
        traceMap.put("endTime", rfc3339(Instant.now()));
        traceMap.put("duration", System.nanoTime() - startRequestNanos);
        traceMap.put("parsing", copyMap(parseMap));
        traceMap.put("validation", copyMap(validationMap));
        traceMap.put("execution", executionData());

        return traceMap;
    }
1344419
def find_by_path(url, map={})
      object = find_object_by_path(url, map)

      if object.is_a?(Array)
        object.map{|o| klass.new(o.merge('cloud_id' => cloud.id))}
      elsif object['id']
        klass.new(object.merge('cloud_id' => cloud.id))
      else
        raise APIError.new(object)
      end
    end