Integrate our powerful mapping solutions into your applications with ease.
Here's a comprehensive example showing how to use all Grab API endpoints:
This example demonstrates:
Before running this code, make sure to:
your_api_key_here
with your actual API keyYou can copy and paste this code into your browser's console to test the API endpoints.
Here is a complete Jetpack Compose example for BragMaps API integration on Android:
<uses-permission android:name = "android.permission.INTERNET" />
to your AndroidManifest.xml
implementation("io.coil-kt:coil-compose:2.5.0")
to your app's build.gradle
file for image loading functionality
This Jetpack Compose view demonstrates:
Before running this code, make sure to:
Here is a complete SwiftUI example for BragMaps API integration on iOS:
This SwiftUI view demonstrates:
Before running this code, make sure to:
your_api_key_here
with your actual API keyHere's a complete Flask server example that serves a web page with BragMaps API integration and handles CORS through a proxy:
from flask import Flask, render_template, request, Response, jsonify
import requests
from urllib.parse import urljoin
app = Flask(__name__)
BRAGMAPS_BASE_URL = "https://bragmaps.com"
REQUEST_TIMEOUT = 30 # seconds
@app.route('/')
def index():
return render_template('index.html')
@app.route('/api/proxy/', methods=['GET', 'POST', 'OPTIONS'])
def proxy(api_path):
if request.method == 'OPTIONS':
# Handle preflight requests
response = Response()
response.headers['Access-Control-Allow-Origin'] = '*'
response.headers['Access-Control-Allow-Methods'] = 'GET, POST, OPTIONS'
response.headers['Access-Control-Allow-Headers'] = 'Content-Type, Authorization'
return response
try:
# Build the target URL
target_url = urljoin(BRAGMAPS_BASE_URL, api_path)
if request.query_string:
target_url = f"{target_url}?{request.query_string.decode('utf-8')}"
# Copy original request headers
headers = {key: value for key, value in request.headers if key.lower() != 'host'}
# Make the request with timeout
resp = requests.request(
method=request.method,
url=target_url,
headers=headers,
data=request.get_data(),
timeout=REQUEST_TIMEOUT
)
# For JSON responses, return immediately without streaming
if 'application/json' in resp.headers.get('Content-Type', ''):
return jsonify(resp.json())
# For non-JSON responses, stream the response
response = Response(resp.iter_content(chunk_size=1024), resp.status_code)
for key, value in resp.headers.items():
if key.lower() not in ('content-length', 'content-encoding', 'transfer-encoding'):
response.headers[key] = value
# Add CORS headers
response.headers['Access-Control-Allow-Origin'] = '*'
return response
except requests.Timeout:
return jsonify({
'error': f'Request timed out after {REQUEST_TIMEOUT} seconds',
'url': target_url
}), 504
except requests.RequestException as e:
return jsonify({
'error': str(e),
'url': target_url
}), 502
except Exception as e:
return jsonify({
'error': 'Internal server error',
'details': str(e)
}), 500
if __name__ == '__main__':
app.run(debug=True, port=8080)
flask==3.0.0
Werkzeug==3.0.1
requests==2.31.0
BragMaps Python Example
BragMaps API Test
This example demonstrates the BragMaps API integration using JavaScript.
Note: Open the browser console to see the API test results.
This Python Flask example demonstrates:
demo_sites/python/
├── app.py # Flask server code with proxy support
├── requirements.txt # Python dependencies
├── templates/ # HTML templates directory
│ └── index.html # Main template with BragMaps integration
└── README.md # Project documentation
# Create virtual environment
python -m venv venv
# Activate on Windows
venv\Scripts\activate
# Activate on macOS/Linux
source venv/bin/activate
pip install -r requirements.txt
python app.py
http://localhost:8080
Here's a complete Spring Boot example that serves a web page with BragMaps API integration and handles CORS through a proxy:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.3</version>
<relativePath/>
</parent>
<groupId>com.example</groupId>
<artifactId>bragmaps-demo</artifactId>
<version>1.0.0</version>
<name>bragmaps-demo</name>
<description>BragMaps API Integration Demo with Spring Boot</description>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<!-- Spring Boot Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.example.bragmapsdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class BragMapsDemoApplication {
public static void main(String[] args) {
SpringApplication.run(BragMapsDemoApplication.class, args);
}
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
package com.example.bragmapsdemo.controller;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Controller
public class BragMapsController {
private static final Logger logger = LoggerFactory.getLogger(BragMapsController.class);
private static final String BRAGMAPS_BASE_URL = "https://bragmaps.com";
private final RestTemplate restTemplate;
@Autowired
public BragMapsController(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
@GetMapping("/")
public String index() {
return "index";
}
@RequestMapping(value = "/api/proxy/**", method = {RequestMethod.GET, RequestMethod.POST, RequestMethod.OPTIONS})
public ResponseEntity proxyRequest(
HttpServletRequest request,
@RequestBody(required = false) byte[] body,
@RequestHeader HttpHeaders headers) {
// Handle CORS preflight
if (request.getMethod().equals("OPTIONS")) {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setAccessControlAllowOrigin("*");
responseHeaders.setAccessControlAllowMethods(List.of(
HttpMethod.GET, HttpMethod.POST, HttpMethod.OPTIONS
));
responseHeaders.setAccessControlAllowHeaders(List.of(
"Content-Type", "Authorization"
));
return new ResponseEntity<>(null, responseHeaders, HttpStatus.OK);
}
try {
// Extract the API path from the request
String apiPath = request.getRequestURI().substring("/api/proxy/".length());
logger.info("Proxying request to: {}", apiPath);
// Build the target URL
URI targetUrl = UriComponentsBuilder
.fromUriString(BRAGMAPS_BASE_URL)
.path(apiPath)
.query(request.getQueryString())
.build()
.toUri();
logger.debug("Full target URL: {}", targetUrl);
// Create headers for the proxy request
HttpHeaders proxyHeaders = new HttpHeaders();
headers.forEach((key, value) -> {
if (!key.equalsIgnoreCase("host")) {
proxyHeaders.put(key, value);
}
});
// Log headers for debugging (excluding sensitive information)
logger.debug("Request headers: {}", proxyHeaders.entrySet().stream()
.filter(e -> !e.getKey().equalsIgnoreCase("Authorization"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
// Create the request entity
HttpEntity requestEntity = new HttpEntity<>(
request.getMethod().equals("POST") ? body : null,
proxyHeaders
);
// Make the request
ResponseEntity response = restTemplate.exchange(
targetUrl,
HttpMethod.valueOf(request.getMethod()),
requestEntity,
byte[].class
);
// Create response headers
HttpHeaders responseHeaders = new HttpHeaders();
response.getHeaders().forEach((key, value) -> {
if (!List.of("content-length", "content-encoding", "transfer-encoding")
.contains(key.toLowerCase())) {
responseHeaders.put(key, value);
}
});
responseHeaders.setAccessControlAllowOrigin("*");
logger.info("Successfully proxied request to: {} (Status: {})", apiPath, response.getStatusCode());
// Return the response
return new ResponseEntity<>(
response.getBody(),
responseHeaders,
response.getStatusCode()
);
} catch (RestClientException e) {
logger.error("Error proxying request: {}", e.getMessage(), e);
HttpHeaders errorHeaders = new HttpHeaders();
errorHeaders.setAccessControlAllowOrigin("*");
return new ResponseEntity<>(
e.getMessage().getBytes(),
errorHeaders,
HttpStatus.INTERNAL_SERVER_ERROR
);
} catch (Exception e) {
logger.error("Unexpected error: {}", e.getMessage(), e);
HttpHeaders errorHeaders = new HttpHeaders();
errorHeaders.setAccessControlAllowOrigin("*");
return new ResponseEntity<>(
"Internal server error".getBytes(),
errorHeaders,
HttpStatus.INTERNAL_SERVER_ERROR
);
}
}
}
# Logging configuration
logging.level.com.example.bragmapsdemo=DEBUG
logging.level.org.springframework.web=DEBUG
logging.level.org.springframework.web.client.RestTemplate=DEBUG
# Server configuration
server.error.include-message=always
server.error.include-binding-errors=always
server.error.include-stacktrace=never
# RestTemplate configuration
spring.codec.max-in-memory-size=10MB
This Spring Boot example demonstrates:
demo_sites/java/
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/
│ │ │ └── example/
│ │ │ └── bragmapsdemo/
│ │ │ ├── BragMapsDemoApplication.java
│ │ │ └── controller/
│ │ │ └── BragMapsController.java
│ │ └── resources/
│ │ ├── application.properties
│ │ └── templates/
│ │ └── index.html
├── pom.xml
└── README.md
cd demo_sites/java
./mvnw spring-boot:run
http://localhost:8080
Here's a complete Go server example that serves a web page with BragMaps API integration and handles CORS through a proxy:
embed
package support.
package main
import (
"embed"
"html/template"
"io"
"log"
"net/http"
"strings"
)
//go:embed templates/*
var templates embed.FS
const bragmapsBaseURL = "https://bragmaps.com"
// CORS middleware
func corsMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Set CORS headers
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
// Handle preflight requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
// proxyHandler forwards requests to BragMaps API
func proxyHandler(w http.ResponseWriter, r *http.Request) {
// Get the API path from the URL
apiPath := strings.TrimPrefix(r.URL.Path, "/api/proxy")
// Create the proxy request
proxyURL := bragmapsBaseURL + apiPath
if r.URL.RawQuery != "" {
proxyURL += "?" + r.URL.RawQuery
}
// Create a new request
proxyReq, err := http.NewRequest(r.Method, proxyURL, r.Body)
if err != nil {
http.Error(w, "Error creating proxy request: "+err.Error(), http.StatusInternalServerError)
return
}
// Copy headers from original request
for header, values := range r.Header {
for _, value := range values {
proxyReq.Header.Add(header, value)
}
}
// Make the request
client := &http.Client{}
resp, err := client.Do(proxyReq)
if err != nil {
http.Error(w, "Error making proxy request: "+err.Error(), http.StatusBadGateway)
return
}
defer resp.Body.Close()
// Copy response headers
for header, values := range resp.Header {
for _, value := range values {
w.Header().Add(header, value)
}
}
// Set status code
w.WriteHeader(resp.StatusCode)
// Copy response body
_, err = io.Copy(w, resp.Body)
if err != nil {
log.Printf("Error copying response: %v", err)
}
}
func main() {
// Parse templates
tmpl, err := template.ParseFS(templates, "templates/*.html")
if err != nil {
log.Fatal(err)
}
// Create a new mux for routing
mux := http.NewServeMux()
// Handle root route
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Set content type
w.Header().Set("Content-Type", "text/html; charset=utf-8")
err := tmpl.ExecuteTemplate(w, "index.html", nil)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
// Handle proxy requests
mux.HandleFunc("/api/proxy/", proxyHandler)
// Create handler with CORS middleware
handler := corsMiddleware(mux)
// Start server
log.Println("Server starting on http://localhost:8080")
if err := http.ListenAndServe(":8080", handler); err != nil {
log.Fatal(err)
}
}
BragMaps Go Example
BragMaps API Test
This example demonstrates the BragMaps API integration using JavaScript.
Note: Open the browser console to see the API test results.
This Go server example demonstrates:
embed
package to embed static filesdemo_sites/go/
├── main.go # Go server code with proxy support
├── templates/ # HTML templates directory
│ └── index.html # Main template with BragMaps integration
└── README.md # Project documentation
cd demo_sites/go
go run main.go
http://localhost:8080