Convert Mapbox results into GeoJSON
961089
function toGeoJSON(json, options = Options) {
  const collection = featureCollection([])
  collection.features = json.features.map(result => {
    return result
  })
  return collection
}
259084
function _getLayerJson(layer, callback) {
    var url = null;
    if(layer.layers !== undefined || ((layer.kind || layer.type) !== undefined)) {
      // layer object contains the layer data
      _.defer(function() { callback(layer); });
      return;
    } else if(layer.table !== undefined && layer.user !== undefined) {
      // layer object points to cartodbjson
      url = cartodbUrl(layer);
    } else if(layer.indexOf) {
      // fetch from url
      url = layer;
    }
    if(url) {
      cdb.core.Loader.get(url, callback);
    } else {
      _.defer(function() { callback(null); });
    }
  }
452303
def _build_from_geojson(self, src):
        
        geojson = json.loads(self.read(src))
        idx = index.Index()
        data_store = {}
        for i, feature in enumerate(geojson['features']):
            feature = self._build_obj(feature)
            idx.insert(i, feature['geometry'].bounds)
            data_store[i] = feature
        return data_store, idx
697495
def probably_geojson(input):
    ''''''
    valid = False
    if not isinstance(input, dict):
        try:
            input = json.loads(input)
        except ValueError:
            return None
    typename = input.get('type', None)
    supported_types = set([
        'Point', 'LineString', 'Polygon', 'MultiPoint', 'MultiLineString',
        'MultiPolygon', 'GeometryCollection', 'Feature', 'FeatureCollection'
    ])
    valid = typename in supported_types
    return input if valid else None
1007391
function(bbox) {
        var coords = this._toIndexKey(bbox);
        var array = this._rtree.search(coords);
        array = this._sortByDistance(array, bbox);
        var result = [];
        var filterMultiPoints = !!this.options.filterPoints;
        for (var i = 0; i < array.length; i++) {
            var arr = array[i];
            var r = arr.data;
            var geometry = this.getGeometry(r);
            var handled = false;
            GeoJsonUtils.forEachGeometry(geometry, {
                onPoints : function(points) {
                    if (!handled
                            && (!filterMultiPoints || GeometryUtils
                                    .bboxContainsPoints(points, bbox))) {
                        result.push(r);
                        handled = true;
                    }
                },
                onLines : function(lines) {
                    if (!handled
                            && GeometryUtils.bboxIntersectsLines(lines, bbox)) {
                        result.push(r);
                        handled = true;
                    }
                },
                onPolygons : function(polygons) {
                    if (!handled
                            && GeometryUtils.bboxIntersectsPolygonsWithHoles(
                                    polygons, bbox)) {
                        result.push(r);
                        handled = true;
                    }
                }
            });
        }
        return result;
    }
543260
private static String toJSON(Object data) {
        try {
            return mapper.writeValueAsString(data);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
419768
def make_geojson(contents):
    
    if isinstance(contents, six.string_types):
        return contents

    if hasattr(contents, '__geo_interface__'):
        features = [_geo_to_feature(contents)]
    else:
        try:
            feature_iter = iter(contents)
        except TypeError:
            raise ValueError('Unknown type for input')

        features = []
        for i, f in enumerate(feature_iter):
            if not hasattr(f, '__geo_interface__'):
                raise ValueError('Unknown type at index {0}'.format(i))
            features.append(_geo_to_feature(f))

    data = {'type': 'FeatureCollection', 'features': features}
    return json.dumps(data)
504217
def from_geojson(cls, filename):
        """"""
        with open(filename) as fd:
            geometry = json.load(fd)

        if 'type' not in geometry:
            raise TypeError("%s is not a valid geojson." % (filename,))

        return cls(to_shape(geometry), WGS84_CRS)
1216086
private function mapGeoposResults($results)
    {
        $ret = [];

        foreach ($results as $coords) {
            $point = [];

            foreach ($coords as $latlon) {
                array_push($point, floatval($latlon));
            }

            array_push($ret, $point);
        }

        return $ret;
    }
1227470
def geojson(self, feature_id):
        """"""
        if self._geojson.get('id', feature_id) == feature_id:
            return self._geojson
        else:
            geo = self._geojson.copy()
            geo['id'] = feature_id
            return geo
150195
public static GeoShape fromJson(String json) {
        try {
            return JsonSerializer.fromString(json, GeoShape.class);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unparseable shape");
        }
    }
489488
function convertObjectToJSON(data) {
      const delimiter = '_'
      let result = {}
      let arrays = {}
      data.forEach(item => {
        const value = item.value
        if (value !== '') {
          if (!item.name) return
          let name = item.name
          let nameParts = name.split(delimiter)
          let currResult = result
          for (let j = 0; j < nameParts.length; j++) {
            const namePart = nameParts[j]
            let arrName
            if (namePart.indexOf('[]') > -1 && j === nameParts.length - 1) {

              arrName = namePart.substr(0, namePart.indexOf('['))
              if (!currResult[arrName]) {
                currResult[arrName] = []
              }
              currResult[arrName].push(value)
            } else {
              if (namePart.indexOf('[') > -1) {
                arrName = namePart.substr(0, namePart.indexOf('['))
                const arrIdx = namePart.replace(/^[a-z]+\[|\]$/gi, '')
                if (!arrays[arrName]) {
                  arrays[arrName] = {}
                }
                if (!currResult[arrName]) {
                  currResult[arrName] = []
                }
                if (j === nameParts.length - 1) {
                  currResult[arrName].push(value)
                } else {
                  if (!arrays[arrName][arrIdx]) {
                    currResult[arrName].push({})
                    arrays[arrName][arrIdx] = currResult[arrName][currResult[arrName].length - 1]
                  }
                }
                currResult = arrays[arrName][arrIdx]
              } else {
                if (j < nameParts.length - 1) {
                  if (!currResult[namePart]) {
                    currResult[namePart] = {}
                  }
                  currResult = currResult[namePart]
                } else {
                  currResult[namePart] = value
                }
              }
            }
          }
        }
      })
      return result
    }
669570
function _getBoundingBox (result) {
  if (!result.viewport) {
    return;
  }
  const upperLeft = result.viewport.topLeftPoint;
  const bottomRight = result.viewport.btmRightPoint;

  return {
    south: bottomRight.lat,
    west: upperLeft.lon,
    north: upperLeft.lat,
    east: bottomRight.lon
  };
}
1304865
function mapOptions() {
          return {
            element: element[0],
            scope: 'usa',
            height: scope.height,
            width: scope.width,
            fills: { defaultFill: '#b9b9b9' },
            data: {},
            done: function (datamap) {
              function redraw() {
                datamap.svg.selectAll('g').attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')');
              }
              if (angular.isDefined(attrs.onClick)) {
                datamap.svg.selectAll('.datamaps-subunit').on('click', function (geography) {
                  scope.onClick()(geography);
                });
              }
              if (angular.isDefined(attrs.zoomable)) {
                datamap.svg.call(d3.behavior.zoom().on('zoom', redraw));
              }
            }
          };
        }
91211
def to_json(self):
    """"""
    result = {
        "mapper_handler_spec": self.handler_spec,
        "mapper_input_reader": self.input_reader_spec,
        "mapper_params": self.params,
        "mapper_shard_count": self.shard_count
    }
    if self.output_writer_spec:
      result["mapper_output_writer"] = self.output_writer_spec
    return result
700963
def fromGeoJson(struct, attributes=None):
    ""
    if isinstance(struct, basestring):
        struct = json.loads(struct)
    type_map = {
        'Point': Point,
        'MultiLineString': Polyline,
        'LineString': Polyline,
        'Polygon': Polygon,
        'MultiPolygon': Polygon,
        'MultiPoint': Multipoint,
        'Box': Envelope
    }
    if struct['type'] == "Feature":
        return fromGeoJson(struct, struct.get('properties', None))
    elif struct['type'] == "FeatureCollection":
        sr = None
        if 'crs' in struct:
            sr = SpatialReference(struct['crs']['properties']['code'])
            members = map(fromGeoJson, struct['members'])
            for member in members:
                member.spatialReference = sr
            return members
        else:
            return map(fromGeoJson, struct['members'])
    elif struct['type'] in type_map and hasattr(type_map[struct['type']], 
                                              'fromGeoJson'):
        instances = type_map[struct['type']].fromGeoJson(struct)
        i = []
        assert instances is not None, "GeoJson conversion returned a Null geom"
        for instance in instances:
            if 'properties' in struct:
                instance.attributes = struct['properties'].copy()
                if '@esri.sr' in instance.attributes:
                    instance.spatialReference = SpatialReference.fromJson(
                                               instance.attributes['@esri.sr'])
                    del instance.attributes['@esri.sr']
            if attributes:
                if not hasattr(instance, 'attributes'):
                    instance.attributes = {}
                for k, v in attributes.iteritems():
                    instance.attributes[k] = v
            i.append(instance)
        if i:
            if len(i) > 1:
                return i
            return i[0]
    raise ValueError("Unconvertible to geometry")
726792
function collectResults(resultsGlob) {
    var glob = require("glob"),
        fs = require("fs"),
        Q = require('q'),
        JunitConverter = require("./formats/junitConverter"),
        response = {},
        count = 0,
        specs,
        files = [],
        converter,
        result;

    for (var i = 0; i < resultsGlob.length; i++) {
        files = files.concat(glob.sync(resultsGlob[i]));
    }

    var converterCallback = function(output) {
        result = output;
    };

    for (i = 0; i < files.length; i++) {
        if (files[i].indexOf(".xml") !== -1) {
            converter = new JunitConverter(files[i]);
            converter.exec(converterCallback);
        } else {
            try {
                result = JSON.parse(fs.readFileSync(files[i]));
            } catch (err) {
                console.log('Error parsing JSON of ' + files[i]);
                result = {};
            }
        }
        response = mergeResults(result, response);
        count++;
    }
    return Q.fcall(function () {
        return response;
    });
}