Blog>
Snippets

GPS Location Tracking

Implement a GPS tracking system where the location is updated in real-time on a map using Angular and WebSocket connections.
import { webSocket } from 'rxjs/webSocket';

// Service that handles WebSocket connections
@Injectable({ providedIn: 'root' })
export class GpsTrackingService {
  private locationSocket$ = webSocket('ws://your-websocket-server-url');

  // Function to receive location updates
  getLocationUpdates() {
    return this.locationSocket$.asObservable();
  }
}
This code represents a service in Angular that sets up a WebSocket connection using RxJS. It provides a method to receive location updates from the server through the WebSocket connection.
import { Component, OnInit } from '@angular/core';
import { GpsTrackingService } from './gps-tracking.service';

@Component({
  selector: 'app-gps-tracker',
  templateUrl: './gps-tracker.component.html',
  styleUrls: ['./gps-tracker.component.css']
})
export class GpsTrackerComponent implements OnInit {
  currentLocation: any = null;

  constructor(private gpsTrackingService: GpsTrackingService) {}

  ngOnInit() {
    this.gpsTrackingService.getLocationUpdates().subscribe(location => {
      this.currentLocation = location;
      // Update the map with the new location here
    });
  }
}
This code snippet is a component in Angular that uses the GpsTrackingService to receive location updates. When a new location is received, it updates the 'currentLocation' property that should be reflected on the map.
<!-- GPS Tracker Component Template -->
<div id="map"></div>

<script>
  // Assuming you have a map initialization function
  function initMap() {
    // Initialize your map with a library like Google Maps or Leaflet
  }

  // You would also need a function to update the map with the new location
  function updateMap(location) {
    // Logic to update the map marker or center based on the new location
  }
</script>
This code snippet should be part of the HTML template for the GpsTrackerComponent. It includes a placeholder for the map and scripts to initialize the map and update it when location changes. You would use actual mapping library code in 'initMap()' and 'updateMap(location)' to manipulate the map.