Convert Bing results into GeoJSON
974074
function toGeoJSON(json, options = Options) {
  const collection = helpers.featureCollection([])
  json.resourceSets[0].resources.map(result => {
    // Point GeoJSON
    const point = parsePoint(result)
    const bbox = parseBBox(result)
    let confidence = confidenceScore(bbox)
    const properties = {
      confidence,
      authenticationResultCode: json.authenticationResultCode,
      brandLogoUri: json.brandLogoUri,
      copyright: json.copyright,
      entityType: result.entityType,
      matchCodes: result.matchCodes,
      name: result.name,
      statusCode: json.statusCode,
      statusDescription: json.statusDescription,
      traceId: json.traceId,
    }
    Object.keys(result.address).forEach(key => properties[key] = result.address[key])

    // Store Point to GeoJSON feature collection
    if (point) {
      point.bbox = bbox
      point.properties = properties
      collection.features.push(point)
    }
  })
  return collection
}
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;
    }
1368497
function mapValidation (results) {
  var res = {};

  normalizeMap(results).forEach(function (ref) {
    var key = ref.key;
    var val = ref.val;

    res[key] = function mappedValidation () {
      var validation = this.$validation;
      if (!this._isMounted) {
        return null
      }
      var paths = val.split('.');
      var first = paths.shift();
      if (first !== '$validation') {
        warn(("unknown validation result path: " + val));
        return null
      }
      var path;
      var value = validation;
      do {
        path = paths.shift();
        value = value[path];
      } while (paths.length > 0 && value !== undefined)
      return value
    };
  });

  return res
}
981031
def query_to_map(text):
    '''
    '''
    dict_obj = {}

    for key, value in split_query(text, True):
        if key not in dict_obj:
            dict_obj[key] = []

        if value:
            dict_obj[key].append(value.replace('+', ' '))
        else:
            dict_obj[key].append('')

    return query_to_map(text)
542684
public function toGeoJson() {
        $Context = $this->_context;


        //If is a invalid object
        if (null === $Context) {
            return $Context;
        }


        //If is not an array(query response) and  is a object
        if (!is_array($Context)) {
            //Check if is a valid entity object
            if (is_object($Context) && isset($Context->id) && isset($Context->type)) {
                $Context = [$Context];
            } else {
                return null;
            }
        }

        $geoJson = (object) ["type" => "FeatureCollection", "features" => []];

        //Build FeatureCollection
//        $countContext = count($Context);
        foreach ($Context as $Entity) { //0.0080490112304688 Seconds
//        for ($i = 0; $i < $countContext; $i++) { //0.025826215744019 Seconds
//            $Entity = $Context[$i];

            if (!(isset($Entity->id) && isset($Entity->type))) {
                continue;
            }
            
            $Feature = (object) ["type" => "Feature", "properties" => ['__metadata'=>[]], "geometry" => null];

            $entityType = null;
            $entityID = null;
            //Roll-out all properties of this feature
            foreach ($Entity as $key => $attr) {
                switch ($key) {
                    case "id":
                        $entityID = $attr;
                        $Feature->properties[$key] = $attr;
                        break;
                    case "type":
                        $entityType = $attr;
                        $Feature->properties[$key] = $attr;
                        break;
                    default:
                        switch ($attr->type) {
                            case "geo:json":
                                $Feature->geometry = $attr->value;
                                $Feature->geometry->type = ucfirst(strtolower($Feature->geometry->type)); //Normalization of geoJson geometry type name.
                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            case "geo:point":
                                $coords = array_reverse(explode(",", $attr->value)); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.

                                array_filter($coords, function($coord) {
                                    return floatval(trim($coord));
                                });

                                $Feature->geometry = (object) [
                                            "type" => "Point",
                                            "coordinates" => $coords
                                ];

                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            case "geo:box":
                                $x = array_reverse(explode(",", $attr->value[0])); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.
                                $y = array_reverse(explode(",", $attr->value[1])); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.
                                //Convert boundary box to polygon using WKT  format POLYGON(x1 y1, x1 y2, x2 y2, x2 y1, x1 y1)
                                $coords = [
                                    [$x[0], $y[0]], //x1 y1
                                    [$x[0], $y[1]], //x1 y2
                                    [$x[1], $y[1]], //x2 y2
                                    [$x[0], $y[0]], //x2 y1                                      
                                    [$x[0], $y[0]] //x1 y1
                                ];

                                $Feature->geometry = (object) [
                                            "type" => "Polygon",
                                            "coordinates" => $coords
                                ];

                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            case "geo:polygon":
                            case "geo:line":
                                //Transform Value Pairs to Polygon/Line Coords
                                $coords = array_filter($attr->value, function($rawvalue) {
                                    $coords = array_reverse(explode(",", $rawvalue)); //Change WGS84 Lat Long to Long Lat as GeoJson specifications.
                                    array_filter($coords, function($coord) {
                                        return floatval(trim($coord));
                                    });
                                    return $coords;
                                });

                                $Feature->geometry = (object) [
                                            "type" => ($attr->type == "geo:polygon") ? "Polygon" : "LineString",
                                            "coordinates" => $coords
                                ];

                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['geo_metadata'] = $attr->metadata;
                                }
                                break;
                            default:
                                $Feature->properties[$key] = $attr->value;
                                if (isset($attr->metadata) && !empty((array) $attr->metadata)) {
                                    $Feature->properties['__metadata'][$key] = $attr->metadata;
                                }

                                //Add type to metadata
                                if(isset($attr->type)){
                                    if(!isset($Feature->properties['__metadata'][$key])){
                                        $Feature->properties['__metadata'][$key] = [];
                                    }

                                    $Feature->properties['__metadata'][$key]['type'] = $attr->type;
                                }

                                break;
                        }
                        break;
                }
            }
            
            $Feature->id = "{$entityType}-{$entityID}";

            //Finally if this context have a valid geometry append to feature collection
            if ($Feature->geometry != null) {
                $Feature->properties = (object) $Feature->properties;
                array_push($geoJson->features, $Feature);
            }
        }

        return $geoJson;
    }
939744
function tileToGeoJSON(tile) {
    var bbox = tileToBBOX(tile);
    var poly = {
        type: 'Polygon',
        coordinates: [[
            [bbox[0], bbox[1]],
            [bbox[0], bbox[3]],
            [bbox[2], bbox[3]],
            [bbox[2], bbox[1]],
            [bbox[0], bbox[1]]
        ]]
    };
    return poly;
}
546859
def get_json(self, layer, where="1 = 1", fields=[], count_only=False, srid='4326'):
        
        params = {
                'where': where,
                'outFields': ", ".join(fields),
                'returnGeometry': True,
                'outSR': srid,
                'f': "pjson",
                'orderByFields': self.object_id_field,
                'returnCountOnly': count_only
            }
        if self.token:
            params['token'] = self.token
        if self.geom_type:
            params.update({'geometryType': self.geom_type})
        response = requests.get(self._build_query_request(layer), params=params)
        return response.json()
1127479
function determineGetMapFormats(json, version) {
	var ret = [];

	if (version == '1.3.0') {
		if (json.WMS_Capabilities.Capability) {
			if (json.WMS_Capabilities.Capability[0]) {
				if (json.WMS_Capabilities.Capability[0].Request) {
					if (json.WMS_Capabilities.Capability[0].Request[0]) {
						if (json.WMS_Capabilities.Capability[0].Request[0].GetMap) {
							if (json.WMS_Capabilities.Capability[0].Request[0].GetMap[0]) {
								if (json.WMS_Capabilities.Capability[0].Request[0].GetMap[0].Format) {
									ret = json.WMS_Capabilities.Capability[0].Request[0].GetMap[0].Format;
								}
							}
						}
					}
				}
			}
		}
	} else {
		if (version == '1.1.1' || version == '1.1.0') {
			if (json.WMT_MS_Capabilities.Capability) {
				if (json.WMT_MS_Capabilities.Capability[0]) {
					if (json.WMT_MS_Capabilities.Capability[0].Request) {
						if (json.WMT_MS_Capabilities.Capability[0].Request[0]) {
							if (json.WMT_MS_Capabilities.Capability[0].Request[0].GetMap) {
								if (json.WMT_MS_Capabilities.Capability[0].Request[0].GetMap[0]) {
									if (json.WMT_MS_Capabilities.Capability[0].Request[0].GetMap[0].Format) {
										ret = json.WMT_MS_Capabilities.Capability[0].Request[0].GetMap[0].Format;
									}
								}
							}
						}
					}
				}
			}

		} else {
			if (version == '1.0.0') {
				if (json.WMT_MS_Capabilities.Capability) {
					if (json.WMT_MS_Capabilities.Capability[0]) {
						if (json.WMT_MS_Capabilities.Capability[0].Request) {
							if (json.WMT_MS_Capabilities.Capability[0].Request[0]) {
								if (json.WMT_MS_Capabilities.Capability[0].Request[0].Map) {
									if (json.WMT_MS_Capabilities.Capability[0].Request[0].Map[0]) {
										if (json.WMT_MS_Capabilities.Capability[0].Request[0].Map[0].Format) {
											if (json.WMT_MS_Capabilities.Capability[0].Request[0].Map[0].Format[0]) {
												var formatsAsObj = json.WMT_MS_Capabilities.Capability[0].Request[0].Map[0].Format[0];
												for ( var key in formatsAsObj) {
													ret.push(key);
												}
											}
										}
									}
								}
							}
						}
					}
				}

			}
		}
	}

	return ret;
}
1010052
def to_json(self):
    
    return {self.NAMESPACE_RANGE_PARAM: self.ns_range.to_json_object(),
            self.BATCH_SIZE_PARAM: self._batch_size}
1337723
function toGeoJSON(json, options = Options) {
  const short = options.short || Options.short
  const collection = helpers.featureCollection([])
  json.results.map(result => {
    // Get Geometries
    const point = parsePoint(result)
    const bbox = parseBBox(result)

    // Calculate Confidence score
    const location_type = result.geometry.location_type
    let confidence = confidenceScore(bbox)
    if (location_type === 'ROOFTOP') { confidence = 10 }

    // GeoJSON Point properties
    const properties = {
      confidence,
      location_type,
      formatted_address: result.formatted_address,
      place_id: result.place_id,
      types: result.types,
    }

    // Google Specific Properties
    const components = parseAddressComponents(result.address_components, short)
    Object.keys(components).forEach(key => properties[key] = components[key])

    // Store Point to GeoJSON feature collection
    if (point) {
      point.bbox = bbox
      point.properties = properties
      collection.features.push(point)
    }
  })
  return collection
}
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]})
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))
178798
function(results) {

            function serializeToXML(results){
                var xml = "<" + results.type + " name=\"" + xmlEscape(results.name) + "\"";

                if (typeof(results.duration)=="number"){
                    xml += " duration=\"" + results.duration + "\"";
                }

                if (results.type == "test"){
                    xml += " result=\"" + results.result + "\" message=\"" + xmlEscape(results.message) + "\">";
                } else {
                    xml += " passed=\"" + results.passed + "\" failed=\"" + results.failed + "\" ignored=\"" + results.ignored + "\" total=\"" + results.total + "\">";
                    for (var prop in results){
                        if (results.hasOwnProperty(prop)){
                            if (results[prop] && typeof results[prop] == "object" && !(results[prop] instanceof Array)){
                                xml += serializeToXML(results[prop]);
                            }
                        }
                    }
                }

                xml += "</" + results.type + ">";

                return xml;
            }

            return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + serializeToXML(results);

        }
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
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)
624056
def to_json(self):
    
    cursor = self._get_cursor()
    cursor_object = False
    if cursor and isinstance(cursor, datastore_query.Cursor):
      cursor = cursor.to_websafe_string()
      cursor_object = True
    return {"key_range": self._key_range.to_json(),
            "query_spec": self._query_spec.to_json(),
            "cursor": cursor,
            "cursor_object": cursor_object}
1283705
def convert2geojson(jsonfile, src_srs, dst_srs, src_file):
        """"""
        if os.path.exists(jsonfile):
            os.remove(jsonfile)
        if sysstr == 'Windows':
            exepath = '"%s/Lib/site-packages/osgeo/ogr2ogr"' % sys.exec_prefix
        else:
            exepath = FileClass.get_executable_fullpath('ogr2ogr')
        # os.system(s)
        s = '%s -f GeoJSON -s_srs "%s" -t_srs %s %s %s' % (
            exepath, src_srs, dst_srs, jsonfile, src_file)
        UtilClass.run_command(s)