expandShortUrl static method
A comprehensive utility class for extracting location information from Google Maps URLs.
This enhanced version supports all known Google Maps URL formats including:
- Standard map URLs with coordinates
- Place URLs with embedded coordinates
- Shortened URLs (goo.gl, maps.app.goo.gl)
- Street View URLs
- Directions URLs
- Embedded map URLs
- Mobile deep links
- Plus codes
- International Google domain variants
Example usage:
final url = 'https://maps.app.goo.gl/mWtb4a1cUE9zMWya7';
final coordinates = await GoogleMapsExtractor.processGoogleMapsUrl(url);
if (coordinates != null) {
print('Latitude: ${coordinates['latitude']}');
print('Longitude: ${coordinates['longitude']}');
} else {
print('Failed to extract coordinates');
}
Expands shortened URLs with enhanced error handling and timeout
Implementation
/// Expands shortened URLs with enhanced error handling and timeout
static Future<String?> expandShortUrl(
String shortUrl, {
int timeoutSeconds = 10,
}) async {
http.Client? client;
try {
client = http.Client();
final http.Request request = http.Request('GET', Uri.parse(shortUrl))
..followRedirects = false;
final http.StreamedResponse response = await client
.send(request)
.timeout(Duration(seconds: timeoutSeconds));
if (response.statusCode == 301 ||
response.statusCode == 302 ||
response.statusCode == 307 ||
response.statusCode == 308) {
final String? location = response.headers['location'];
return location;
}
// Some services return 200 with a redirect in the body
if (response.statusCode == 200) {
final String responseBody = await response.stream.bytesToString();
// Look for meta refresh redirects
final RegExp metaRefreshRegex = RegExp(
r"url=([^\'>\s]+)",
caseSensitive: false,
);
final RegExpMatch? match = metaRefreshRegex.firstMatch(responseBody);
if (match != null) {
return match.group(1);
}
// Look for JavaScript redirects - FIXED REGEX
final RegExp jsRedirectRegex = RegExp(
r"window\.location\.href\s*=\s*[\']([^\']+)[\']",
);
final RegExpMatch? jsMatch = jsRedirectRegex.firstMatch(responseBody);
if (jsMatch != null) {
return jsMatch.group(1);
}
}
} catch (e) {
print('Error expanding URL: $e');
} finally {
client?.close();
}
return null;
}