Code Examples

Practical examples to help you implement Nexus services in your applications

Overview

These code examples demonstrate how to use the Nexus APIs and SDKs to implement common features in your applications. Each example includes code snippets for multiple programming languages and platforms, along with explanations and links to related documentation.

All examples are available on our GitHub repository where you can find complete projects and additional resources.

Categories

Maps & Visualization

Interactive Map with Custom Markers

This example demonstrates how to create an interactive map with custom markers, info windows, and click events using the Nexus Maps API.

JavaScript React Maps API Markers
// Initialize the map
const map = new nexus.maps.Map(document.getElementById('map'), {
  center: { lat: 37.7749, lng: -122.4194 },
  zoom: 12,
  style: 'standard'
});

// Add custom markers
const locations = [
  { position: { lat: 37.7749, lng: -122.4194 }, title: 'San Francisco' },
  { position: { lat: 37.7694, lng: -122.4862 }, title: 'Golden Gate Park' },
  { position: { lat: 37.8199, lng: -122.4783 }, title: 'Golden Gate Bridge' }
];

// Create markers for each location
locations.forEach(location => {
  const marker = new nexus.maps.Marker({
    position: location.position,
    map: map,
    title: location.title,
    icon: {
      path: nexus.maps.SymbolPath.CIRCLE,
      fillColor: '#0096dc',
      fillOpacity: 0.9,
      strokeWeight: 2,
      strokeColor: '#ffffff',
      scale: 8
    }
  });
  
  // Add click event to marker
  marker.addListener('click', () => {
    const infoWindow = new nexus.maps.InfoWindow({
      content: `

${location.title}

Lat: ${location.position.lat}
Lng: ${location.position.lng}

` }); infoWindow.open(map, marker); }); });
import React, { useEffect } from 'react';
import { NexusMap, Marker, InfoWindow } from '@nexus/react-sdk';

const locations = [
  { position: { lat: 37.7749, lng: -122.4194 }, title: 'San Francisco' },
  { position: { lat: 37.7694, lng: -122.4862 }, title: 'Golden Gate Park' },
  { position: { lat: 37.8199, lng: -122.4783 }, title: 'Golden Gate Bridge' }
];

function MapWithMarkers() {
  const [selectedMarker, setSelectedMarker] = React.useState(null);
  
  return (
    
      {locations.map((location, index) => (
         setSelectedMarker(location)}
        />
      ))}
      
      {selectedMarker && (
         setSelectedMarker(null)}
        >
          

{selectedMarker.title}

Lat: {selectedMarker.position.lat}
Lng: {selectedMarker.position.lng}

)}
); }
class MapActivity : AppCompatActivity(), OnMapReadyCallback {
    
    private lateinit var nexusMap: NexusMap
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_map)
        
        val mapFragment = supportFragmentManager
            .findFragmentById(R.id.map) as SupportMapFragment
        mapFragment.getMapAsync(this)
    }
    
    override fun onMapReady(map: NexusMap) {
        nexusMap = map
        
        // Set map style and center
        nexusMap.setMapStyle(MapStyle.STANDARD)
        nexusMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
            LatLng(37.7749, -122.4194), 12f))
        
        // Define locations
        val locations = listOf(
            MarkerData(LatLng(37.7749, -122.4194), "San Francisco"),
            MarkerData(LatLng(37.7694, -122.4862), "Golden Gate Park"),
            MarkerData(LatLng(37.8199, -122.4783), "Golden Gate Bridge")
        )
        
        // Add markers for each location
        locations.forEach { location ->
            val marker = nexusMap.addMarker(
                MarkerOptions()
                    .position(location.position)
                    .title(location.title)
                    .icon(BitmapDescriptorFactory.defaultMarker(
                        BitmapDescriptorFactory.HUE_AZURE))
            )
        }
        
        // Set marker click listener
        nexusMap.setOnMarkerClickListener { marker ->
            marker.showInfoWindow()
            true
        }
    }
    
    data class MarkerData(val position: LatLng, val title: String)
}
import UIKit
import NexusSDK

class MapViewController: UIViewController, NXMapViewDelegate {
    
    var mapView: NXMapView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Initialize map view
        mapView = NXMapView(frame: view.bounds)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.delegate = self
        view.addSubview(mapView)
        
        // Set map style and center
        mapView.mapStyle = .standard
        let sanFrancisco = NXLatLng(latitude: 37.7749, longitude: -122.4194)
        mapView.camera = NXCameraPosition(target: sanFrancisco, zoom: 12)
        
        // Define locations
        let locations = [
            (position: NXLatLng(latitude: 37.7749, longitude: -122.4194), title: "San Francisco"),
            (position: NXLatLng(latitude: 37.7694, longitude: -122.4862), title: "Golden Gate Park"),
            (position: NXLatLng(latitude: 37.8199, longitude: -122.4783), title: "Golden Gate Bridge")
        ]
        
        // Add markers for each location
        for location in locations {
            let marker = NXMarker()
            marker.position = location.position
            marker.title = location.title
            marker.icon = NXIcon(named: "circle_marker")
            marker.iconColor = UIColor(red: 0, green: 150/255, blue: 220/255, alpha: 1)
            marker.map = mapView
        }
    }
    
    // MARK: - NXMapViewDelegate
    
    func mapView(_ mapView: NXMapView, didTap marker: NXMarker) -> Bool {
        // Show info window when marker is tapped
        return false // return false to show default info window
    }
}
View full example on GitHub →

Heatmap Visualization

This example shows how to create a heatmap visualization to display density of data points on a map, which is useful for visualizing traffic patterns, user density, or any other geospatial data.

JavaScript Maps API Heatmap Data Visualization
// Initialize the map
const map = new nexus.maps.Map(document.getElementById('map'), {
  center: { lat: 37.7749, lng: -122.4194 },
  zoom: 12,
  style: 'standard'
});

// Generate random data points around San Francisco
function getRandomPoints(center, numPoints, radius) {
  const points = [];
  for (let i = 0; i < numPoints; i++) {
    const angle = Math.random() * Math.PI * 2;
    const dist = Math.random() * radius;
    const lat = center.lat + dist * Math.cos(angle) * 0.01;
    const lng = center.lng + dist * Math.sin(angle) * 0.01;
    const weight = Math.random();
    points.push({
      location: new nexus.maps.LatLng(lat, lng),
      weight: weight
    });
  }
  return points;
}

// Create heatmap data
const heatmapData = getRandomPoints(
  { lat: 37.7749, lng: -122.4194 }, // San Francisco
  500, // Number of points
  10   // Radius
);

// Create the heatmap layer
const heatmap = new nexus.maps.HeatmapLayer({
  data: heatmapData,
  map: map,
  radius: 20,
  opacity: 0.7,
  gradient: [
    'rgba(0, 255, 255, 0)',
    'rgba(0, 255, 255, 1)',
    'rgba(0, 191, 255, 1)',
    'rgba(0, 127, 255, 1)',
    'rgba(0, 63, 255, 1)',
    'rgba(0, 0, 255, 1)',
    'rgba(0, 0, 223, 1)',
    'rgba(0, 0, 191, 1)',
    'rgba(0, 0, 159, 1)',
    'rgba(0, 0, 127, 1)'
  ]
});

// Add UI controls to toggle heatmap settings
const toggleHeatmap = document.getElementById('toggle-heatmap');
toggleHeatmap.addEventListener('click', () => {
  heatmap.setMap(heatmap.getMap() ? null : map);
});

const changeRadius = document.getElementById('radius-slider');
changeRadius.addEventListener('input', () => {
  heatmap.set('radius', parseInt(changeRadius.value));
});

const changeOpacity = document.getElementById('opacity-slider');
changeOpacity.addEventListener('input', () => {
  heatmap.set('opacity', parseFloat(changeOpacity.value));
});
import React, { useState, useEffect } from 'react';
import { NexusMap, HeatmapLayer } from '@nexus/react-sdk';

function getRandomPoints(center, numPoints, radius) {
  const points = [];
  for (let i = 0; i < numPoints; i++) {
    const angle = Math.random() * Math.PI * 2;
    const dist = Math.random() * radius;
    const lat = center.lat + dist * Math.cos(angle) * 0.01;
    const lng = center.lng + dist * Math.sin(angle) * 0.01;
    const weight = Math.random();
    points.push({
      location: { lat, lng },
      weight: weight
    });
  }
  return points;
}

function HeatmapExample() {
  const [showHeatmap, setShowHeatmap] = useState(true);
  const [radius, setRadius] = useState(20);
  const [opacity, setOpacity] = useState(0.7);
  const [heatmapData, setHeatmapData] = useState([]);
  
  useEffect(() => {
    // Generate random data points around San Francisco
    const data = getRandomPoints(
      { lat: 37.7749, lng: -122.4194 }, // San Francisco
      500, // Number of points
      10   // Radius
    );
    setHeatmapData(data);
  }, []);
  
  return (
    
setRadius(parseInt(e.target.value, 10))} /> {radius}px
setOpacity(parseFloat(e.target.value))} /> {opacity}
{showHeatmap && ( )}
); }
View full example on GitHub →

Vehicle Tracking

Real-time Vehicle Tracking

This example shows how to implement real-time vehicle tracking with animated marker movement, using WebSockets to receive live updates from the Nexus Fleet API.

JavaScript Fleet API WebSockets Real-time Updates
// Initialize the map
const map = new nexus.maps.Map(document.getElementById('map'), {
  center: { lat: 37.7749, lng: -122.4194 },
  zoom: 12,
  style: 'standard'
});

// Store vehicle markers
const vehicleMarkers = new Map();

// Connect to WebSocket for real-time updates
const socket = new WebSocket('wss://api.nexus-platform.com/v2/fleet/vehicles/stream?token=' + apiKey);

socket.onopen = () => {
  console.log('Connected to vehicle tracking stream');
  
  // Request initial vehicle data
  socket.send(JSON.stringify({
    action: 'subscribe',
    fleetId: 'your_fleet_id'
  }));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  
  // Handle different message types
  switch (data.type) {
    case 'vehicles_initial':
      // Initial vehicle data
      handleInitialVehicles(data.vehicles);
      break;
    case 'vehicle_update':
      // Update for a single vehicle
      updateVehicle(data.vehicle);
      break;
    case 'vehicle_added':
      // New vehicle added to fleet
      addVehicle(data.vehicle);
      break;
    case 'vehicle_removed':
      // Vehicle removed from fleet
      removeVehicle(data.vehicleId);
      break;
  }
};

socket.onclose = () => {
  console.log('Disconnected from vehicle tracking stream');
};

// Handle initial list of vehicles
function handleInitialVehicles(vehicles) {
  vehicles.forEach(vehicle => {
    addVehicle(vehicle);
  });
  
  // Adjust map to fit all vehicles
  if (vehicles.length > 0) {
    const bounds = new nexus.maps.LatLngBounds();
    vehicles.forEach(vehicle => {
      bounds.extend(new nexus.maps.LatLng(
        vehicle.location.lat,
        vehicle.location.lng
      ));
    });
    map.fitBounds(bounds);
  }
}

// Add a new vehicle to the map
function addVehicle(vehicle) {
  // Create marker for vehicle
  const marker = new nexus.maps.Marker({
    position: {
      lat: vehicle.location.lat,
      lng: vehicle.location.lng
    },
    map: map,
    title: vehicle.name,
    icon: {
      path: nexus.maps.SymbolPath.FORWARD_CLOSED_ARROW,
      fillColor: getVehicleColor(vehicle.type),
      fillOpacity: 0.9,
      strokeWeight: 2,
      strokeColor: '#ffffff',
      scale: 6,
      rotation: vehicle.heading || 0
    }
  });
  
  // Add info window
  const infoWindow = new nexus.maps.InfoWindow({
    content: createVehicleInfoContent(vehicle)
  });
  
  marker.addListener('click', () => {
    infoWindow.open(map, marker);
  });
  
  // Store marker reference
  vehicleMarkers.set(vehicle.id, {
    marker: marker,
    infoWindow: infoWindow,
    vehicle: vehicle
  });
}

// Update an existing vehicle
function updateVehicle(vehicle) {
  const vehicleData = vehicleMarkers.get(vehicle.id);
  
  if (!vehicleData) {
    // Vehicle not found, add it
    addVehicle(vehicle);
    return;
  }
  
  const marker = vehicleData.marker;
  const infoWindow = vehicleData.infoWindow;
  const currentPosition = marker.getPosition();
  const newPosition = new nexus.maps.LatLng(
    vehicle.location.lat,
    vehicle.location.lng
  );
  
  // Update stored vehicle data
  vehicleData.vehicle = vehicle;
  
  // Update info window content if it's open
  if (infoWindow.getMap()) {
    infoWindow.setContent(createVehicleInfoContent(vehicle));
  }
  
  // Animate marker movement
  animateMarkerMovement(marker, currentPosition, newPosition, vehicle.heading);
}

// Remove a vehicle from the map
function removeVehicle(vehicleId) {
  const vehicleData = vehicleMarkers.get(vehicleId);
  
  if (vehicleData) {
    vehicleData.marker.setMap(null);
    vehicleMarkers.delete(vehicleId);
  }
}

// Animate marker movement
function animateMarkerMovement(marker, start, end, heading) {
  const frames = 20; // Number of animation frames
  let progress = 0;
  
  // Update marker heading
  const icon = marker.getIcon();
  icon.rotation = heading || 0;
  marker.setIcon(icon);
  
  const animationStep = () => {
    progress += 1 / frames;
    
    if (progress < 1) {
      const lat = start.lat() + (end.lat() - start.lat()) * progress;
      const lng = start.lng() + (end.lng() - start.lng()) * progress;
      
      marker.setPosition(new nexus.maps.LatLng(lat, lng));
      
      requestAnimationFrame(animationStep);
    } else {
      marker.setPosition(end);
    }
  };
  
  requestAnimationFrame(animationStep);
}

// Create info window content for a vehicle
function createVehicleInfoContent(vehicle) {
  return `
    

${vehicle.name}

ID: ${vehicle.id}

Type: ${vehicle.type}

Status: ${vehicle.status}

Speed: ${vehicle.speed} km/h

Battery: ${vehicle.battery}%

Last Updated: ${new Date(vehicle.lastUpdated).toLocaleString()}

`; } // Get color based on vehicle type function getVehicleColor(type) { const colors = { 'car': '#0096dc', 'truck': '#ff9900', 'van': '#33cc33', 'bike': '#cc3399', 'scooter': '#9966ff' }; return colors[type] || '#0096dc'; }
View full example on GitHub →

Next Steps