BragMaps API Documentation

Integrate our powerful mapping solutions into your applications with ease.

API Key Status

Checking API key status...

••••••••••••••••

Frontend Development

JavaScript Examples

Here's a comprehensive example showing how to use all Grab API endpoints:

Try it out: You can copy and paste this code directly into your browser's console to test the API endpoints. Scroll down to see the generated HTML output.

This example demonstrates:

  • Fetching map styles and tiles
  • Searching for places (geocoding)
  • Searching for nearby places
  • Getting routes between points
  • Fetching street-level images

Before running this code, make sure to:

  1. Replace your_api_key_here with your actual API key

You can copy and paste this code into your browser's console to test the API endpoints.

Android Kotlin Example

Here is a complete Jetpack Compose example for BragMaps API integration on Android:

Important: When using BragMaps in your Android app, make sure to:
  • Add <uses-permission android:name = "android.permission.INTERNET" /> to your AndroidManifest.xml
  • Add implementation("io.coil-kt:coil-compose:2.5.0") to your app's build.gradle file for image loading functionality
Android Example built with: AGP 8.10.1, Kotlin 2.0.21, compileSdk 35

This Jetpack Compose view demonstrates:

  • Basic Android Compose setup
  • UI theming and preview

Before running this code, make sure to:

  1. Replace any placeholder values with your actual API key if needed
iOS Swift Example

Here is a complete SwiftUI example for BragMaps API integration on iOS:

Important: When using BragMaps in your iOS app, make sure to enable Network Outgoing Connections (Client) in your Xcode project's capabilities. This is required for the API to work properly.
iOS Example built with: Xcode 16.4

This SwiftUI view demonstrates:

  • Fetching map styles and tiles
  • Searching for places (geocoding)
  • Searching for nearby places
  • Getting routes between points
  • Fetching street-level images

Before running this code, make sure to:

  1. Replace your_api_key_here with your actual API key
Python Flask Example

Here's a complete Flask server example that serves a web page with BragMaps API integration and handles CORS through a proxy:

Important: This example requires Python 3.8 or later and pip for package management. The example includes optimized handling of JSON responses and request timeouts.
app.py
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)
requirements.txt
flask==3.0.0
Werkzeug==3.0.1
requests==2.31.0
templates/index.html



    
    
    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.
Python Example built with: Python 3.8+, Flask 3.0.0, Requests 2.31.0

This Python Flask example demonstrates:

  • Setting up a Flask server with CORS support
  • Implementing a proxy to handle BragMaps API requests
  • Optimized handling of JSON responses
  • Request timeout handling
  • Comprehensive error handling
  • Serving HTML templates with visual feedback
  • BragMaps API integration via JavaScript
Project Structure
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
Setup and Running
  1. Create and activate a virtual environment:
    # Create virtual environment
    python -m venv venv
    
    # Activate on Windows
    venv\Scripts\activate
    
    # Activate on macOS/Linux
    source venv/bin/activate
  2. Install dependencies:
    pip install -r requirements.txt
  3. Run the Flask application:
    python app.py
  4. Open your browser and visit:
    http://localhost:8080
Java Spring Boot Example

Here's a complete Spring Boot example that serves a web page with BragMaps API integration and handles CORS through a proxy:

Important: This example requires Java 17 or later and Maven 3.6 or later.
pom.xml
<?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>
BragMapsDemoApplication.java
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();
    }
}
BragMapsController.java
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
            );
        }
    }
}
application.properties
# 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
Java Example built with: Java 17, Spring Boot 3.2.3, Thymeleaf

This Spring Boot example demonstrates:

  • Setting up a Spring Boot server with CORS support
  • Implementing a proxy to handle BragMaps API requests
  • Using Thymeleaf templates with visual feedback
  • BragMaps API integration via JavaScript
  • Streaming responses for better performance
  • Comprehensive error handling and logging
Project Structure
demo_sites/java/
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   └── com/
│   │   │       └── example/
│   │   │           └── bragmapsdemo/
│   │   │               ├── BragMapsDemoApplication.java
│   │   │               └── controller/
│   │   │                   └── BragMapsController.java
│   │   └── resources/
│   │       ├── application.properties
│   │       └── templates/
│   │           └── index.html
├── pom.xml
└── README.md
Setup and Running
  1. Make sure you have Java 17 and Maven installed
  2. Create the project structure as shown above
  3. Copy the code into the respective files
  4. Build and run the application:
    cd demo_sites/java
    ./mvnw spring-boot:run
  5. Open your browser and visit:
    http://localhost:8080
Go Server Example

Here's a complete Go server example that serves a web page with BragMaps API integration and handles CORS through a proxy:

Important: This example requires Go 1.16 or later for the embed package support.
main.go
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)
    }
}
templates/index.html



    
    
    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.
Go Example built with: Go 1.16+, embed package

This Go server example demonstrates:

  • Using Go's embed package to embed static files
  • Setting up a basic HTTP server with CORS support
  • Implementing a proxy to handle BragMaps API requests
  • Serving HTML templates with visual feedback
  • BragMaps API integration via JavaScript
Project Structure
demo_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
Running the Example
  1. Create the project structure as shown above
  2. Copy the code into the respective files
  3. Navigate to the project directory:
    cd demo_sites/go
  4. Run the server:
    go run main.go
  5. Open your browser and visit:
    http://localhost:8080