Export trackline data to GeoJSON file
765925
def export(cls, folder, particles, datetimes):
        
        normalized_locations = [particle.normalized_locations(datetimes) for particle in particles]

        track_coords = []
        for x in xrange(0, len(datetimes)):
            points = MultiPoint([loc[x].point.coords[0] for loc in normalized_locations])
            track_coords.append(points.centroid.coords[0])

        ls = LineString(track_coords)

        if not os.path.exists(folder):
            os.makedirs(folder)
        filepath = os.path.join(folder, "trackline.geojson")
        f = open(filepath, "wb")
        f.write(json.dumps(mapping(ls)))
        f.close()
        return filepath
1176481
def to_geojson(products):
        
        feature_list = []
        for i, (product_id, props) in enumerate(products.items()):
            props = props.copy()
            props['id'] = product_id
            poly = geomet.wkt.loads(props['footprint'])
            del props['footprint']
            del props['gmlfootprint']
            # Fix "'datetime' is not JSON serializable"
            for k, v in props.items():
                if isinstance(v, (date, datetime)):
                    props[k] = v.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
            feature_list.append(
                geojson.Feature(geometry=poly, id=i, properties=props)
            )
        return geojson.FeatureCollection(feature_list)
725739
function separateScriptAndMapFromScriptFile(scriptFile, multiline, mapPath) {
    const node = getNodeFromScriptFile(scriptFile);
    mapPath = mapPath || path.basename(scriptFile) + '.map';
    return {
        script: node.toString().replace(/\r\n/gm, '\n') + (
            multiline
            ? ('/*# sourceMappingURL=' + mapPath + ' */')
            : ('//# sourceMappingURL=' + mapPath)
           ),
        map: JSON.stringify(getCodeMap(node).map.toJSON()),
    };
}
1235834
function PathView(geometryModel) {
  var self = this;
  // events to link
  var events = [
    'click',
    'dblclick',
    'mousedown',
    'mouseover',
    'mouseout',
  ];

  this._eventHandlers = {};
  this.model = geometryModel;
  this.points = [];



  var style = _.clone(geometryModel.get('style')) || {};

  this.geom = new GeoJSON (
    geometryModel.get('geojson'),
    style
  );

  /*_.each(this.geom._layers, function(g) {
    g.setStyle(geometryModel.get('style'));
    g.on('edit', function() {
      geometryModel.set('geojson', L.GeoJSON.toGeoJSON(self.geom));
    }, self);
  });
  */

  _.bindAll(this, '_updateModel');
  var self = this;

  function bindPath(p) {
    google.maps.event.addListener(p, 'insert_at', self._updateModel);
    /*
    google.maps.event.addListener(p, 'remove_at', this._updateModel);
    google.maps.event.addListener(p, 'set_at', this._updateModel);
    */
  }

  // TODO: check this conditions

  if(this.geom.getPaths) {
    var paths = this.geom.getPaths();

    if (paths && paths[0]) {
      // More than one path
      for(var i = 0; i < paths.length; ++i) {
        bindPath(paths[i]);
      }
    } else {
      // One path
      bindPath(paths);
      google.maps.event.addListener(this.geom, 'mouseup', this._updateModel);
    }
  } else {
    // More than one path
    if (this.geom.length) {
      for(var i = 0; i < this.geom.length; ++i) {
        bindPath(this.geom[i].getPath());
        google.maps.event.addListener(this.geom[i], 'mouseup', this._updateModel);
      }
    } else {
      // One path
      bindPath(this.geom.getPath());
      google.maps.event.addListener(this.geom, 'mouseup', this._updateModel);
    }
  }

  /*for(var i = 0; i < events.length; ++i) {
    var e = events[i];
    this.geom.on(e, self._eventHandler(e));
  }*/

}
1205132
def read_geojson(cls, path_or_json_or_string):
        """"""
        assert path_or_json_or_string
        data = None
        if isinstance(path_or_json_or_string, (dict, list)):
            data = path_or_json_or_string
        try:
            data = json.loads(path_or_json_or_string)
        except ValueError:
            pass
        try:
            path = path_or_json_or_string
            if path.endswith('.gz') or path.endswith('.gzip'):
                import gzip
                contents = gzip.open(path, 'r').read().decode('utf-8')
            else:
                contents = open(path, 'r').read()
            data = json.loads(contents)
        except FileNotFoundError:
            pass
        # TODO web address
        assert data, 'MapData accepts a valid geoJSON object, geoJSON string, or path to a geoJSON file'
        return cls(cls._read_geojson_features(data))
256817
function getMarkerLines(
  loc: NodeLocation,
  source: Array<string>,
  opts: Object,
): { start: number, end: number, markerLines: Object }
830431
def split_tracks(lat,lon,*args):
        ''''''
        tracks = []
        lt,ln = [lat[0]],[lon[0]]
        zz = [[z[0]] for z in args]
        for i in range(1,len(lon)):
            lt.append(lat[i])
            for z,a in zip(zz,args):
                z.append(a[i])
            d1 = abs(lon[i] - lon[i-1])
            d2 = abs((lon[i-1] + 360) - lon[i])
            d3 = abs(lon[i-1] - (lon[i] + 360))
            if d2 < d1:
                ln.append(lon[i]-360)
                tracks.append([np.array(lt),np.array(ln)] \
                    + [np.array(z) for z in zz])
                lt = [lat[i-1],lat[i]]
                ln = [lon[i-1]+360,lon[i]]
                zz = [[z[i-1]] for z in args]
            elif d3 < d1:
                ln.append(lon[i]+360)
                tracks.append([np.array(lt),np.array(ln)] \
                    + [np.array(z) for z in zz])
                lt = [lat[i-1],lat[i]]
                ln = [lon[i-1]-360,lon[i]]
                zz = [[z[i-1],z[i]] for z in args]
            else:
                ln.append(lon[i])
        if len(lt):
            tracks.append([np.array(lt),np.array(ln)] \
                + [np.array(z) for z in zz])
        return tracks
210211
function (renderable) {
                if (!(renderable instanceof WorldWind.Path)) {
                    throw new ArgumentError(
                        Logger.logMessage(Logger.LEVEL_SEVERE, "GeoJSONExporter", "exportPath",
                            "invalidTypeOfRenderable"));
                }

                var sb = '{';
                sb = sb + '"' + GeoJSONConstants.FIELD_TYPE + '":"' + GeoJSONConstants.TYPE_LINE_STRING + '",';
                sb = sb + '"' + GeoJSONConstants.FIELD_COORDINATES + '":[';
                for (var i = 0; i < renderable.positions.length; i++) {
                    sb = sb + '[' + renderable.positions[i].longitude + ',' +
                        renderable.positions[i].latitude + ',' +
                        renderable.positions[i].altitude + ']';
                    if (i !== renderable.positions.length - 1) {
                        sb = sb + ',';
                    }
                }
                sb = sb + ']';
                sb = sb + '}';
                return sb;
            }
217641
def export_gpx_file(self):
        
        gpx = create_elem('gpx', GPX_ELEM_ATTRIB)
        if not self.metadata.bounds:
            self.metadata.bounds = [j for i in self for j in i]
        gpx.append(self.metadata.togpx())
        track = create_elem('trk')
        gpx.append(track)
        for segment in self:
            chunk = create_elem('trkseg')
            track.append(chunk)
            for place in segment:
                chunk.append(place.togpx())

        return etree.ElementTree(gpx)
1179309
def to_dict(self):
        
        viewconf = json.loads(json.dumps(self.viewconf))

        for track in self.tracks:
            if track.position is None:
                raise ValueError(
                    "Track has no position: {}".format(track.viewconf["type"])
                )
            viewconf["tracks"][track.position] += [track.to_dict()]

        return viewconf
1216481
public static void writeGeoJson(Connection connection, String fileName, String tableReference, String encoding) throws IOException, SQLException {
        GeoJsonDriverFunction geoJsonDriver = new GeoJsonDriverFunction();
        geoJsonDriver.exportTable(connection,tableReference, URIUtilities.fileFromString(fileName), new EmptyProgressVisitor(),encoding);
    }
1248896
function () {
		var series = this,
			graphPath = [],
			segmentPath,
			singlePoints = []; // used in drawTracker

		// Divide into segments and build graph and area paths
		each(series.segments, function (segment) {
			
			segmentPath = series.getSegmentPath(segment);
			
			// add the segment to the graph, or a single point for tracking
			if (segment.length > 1) {
				graphPath = graphPath.concat(segmentPath);
			} else {
				singlePoints.push(segment[0]);
			}
		});

		// Record it for use in drawGraph and drawTracker, and return graphPath
		series.singlePoints = singlePoints;
		series.graphPath = graphPath;
		
		return graphPath;
		
	}
210105
def read_geojson(filename):
    
    json_file = open(filename)
    data = json.load(json_file)
    json_file.close()
    times = data["properties"]["times"]
    main_data = dict(timesteps=[], masks=[], x=[], y=[], i=[], j=[])
    attribute_data = dict()
    for feature in data["features"]:
        for main_name in main_data.keys():
            main_data[main_name].append(np.array(feature["properties"][main_name]))
        for k, v in feature["properties"]["attributes"].items():
            if k not in attribute_data.keys():
                attribute_data[k] = [np.array(v)]
            else:
                attribute_data[k].append(np.array(v))
    kwargs = {}
    for kw in ["dx", "step", "u", "v"]:
        if kw in data["properties"].keys():
            kwargs[kw] = data["properties"][kw]
    sto = STObject(main_data["timesteps"], main_data["masks"], main_data["x"], main_data["y"],
                   main_data["i"], main_data["j"], times[0], times[-1], **kwargs)
    for k, v in attribute_data.items():
        sto.attributes[k] = v
    return sto
602895
def draw_linecollection(data, obj):
    
    content = []

    edgecolors = obj.get_edgecolors()
    linestyles = obj.get_linestyles()
    linewidths = obj.get_linewidths()
    paths = obj.get_paths()

    for i, path in enumerate(paths):
        color = edgecolors[i] if i < len(edgecolors) else edgecolors[0]
        style = linestyles[i] if i < len(linestyles) else linestyles[0]
        width = linewidths[i] if i < len(linewidths) else linewidths[0]

        data, options = mypath.get_draw_options(data, obj, color, None, style, width)

        # TODO what about masks?
        data, cont, _, _ = mypath.draw_path(
            data, path, draw_options=options, simplify=False
        )
        content.append(cont + "\n")

    return data, content
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")
143693
def row_to_geojson(row, lon, lat, precision, date_format='epoch'):
    

    # Let pandas handle json serialization
    row_json = json.loads(row.to_json(date_format=date_format, date_unit='s'))
    return geojson.Feature(geometry=geojson.Point((round(row_json[lon], precision), round(row_json[lat], precision))),
                           properties={key: row_json[key] for key in row_json.keys() if key not in [lon, lat]})
326488
async function exportCustomSelectorsToJsonFile(to, customSelectors) {
	const jsonContent = JSON.stringify({
		'custom-selectors': customSelectors
	}, null, '  ');
	const json = `${jsonContent}\n`;

	await writeFile(to, json);
}