DAA - Dijkstra Aat Draft 3
DAA - Dijkstra Aat Draft 3
COLLEGE OF ENGINEERING
(Autonomous Institute, Affiliated to VTU, Belagavi)
Post Box No.: 1908, Bull Temple Road, Bengaluru – 560 019
ABSTRACT
This report explores the implementation of a system that integrates the Google Maps API with Dijkstra's
algorithm to improve the efficiency of locating nearby businesses. In modern urban environments, quickly
identifying local services, such as restaurants, stores, and professional services, is essential for both residents and
visitors. The Google Maps API provides a robust platform for accessing geographic data, including business
locations, road networks, and traffic conditions. Concurrently, Dijkstra's algorithm, a well-established method
for finding the shortest paths in weighted graphs, offers a reliable computational approach to route optimization.
The study aims to create a system that effectively searches for and recommends nearby businesses based on
user-defined criteria, such as minimal travel distance or time. The methodology involves several key steps:
retrieving geographic data via the Google Maps API, constructing a weighted graph where nodes represent
locations and edges represent roads with weights corresponding to travel distances or times, applying Dijkstra's
algorithm to compute the shortest paths from the user's location to potential business locations, and processing
these results to recommend the most convenient businesses to the user.
Integrating the Google Maps API with Dijkstra's algorithm enhances the precision and speed of business
searches, significantly improving the user experience by providing real-time, efficient route suggestions. The
report includes a detailed analysis and performance evaluation of the system, demonstrating its effectiveness in
various urban scenarios. It also addresses potential challenges, such as handling real-time traffic updates and
managing large datasets, proposing solutions to these issues.
This study highlights the potential of combining advanced graph algorithms with comprehensive geolocation
APIs to solve practical problems in urban navigation and local business discovery, showcasing the benefits of
such integrated systems in enhancing urban living.
2
TABLE OF CONTENTS
CH.
TITLE PAGE NO.
NO.
Abstract
Table of Contents
I
1 Introduction
II
1.1 About the domain
III
1.3 Scope and Objectives
IV
2 Detailed design architecture
IV
2.1 Proposed system architecture
V-VI
2.2 Design architecture
VII-IX
2.3 Methodology
3 Implementation
Source code X-XIX
3.1
XX-XXII
3.2 About the code
XXIII
3.3 Output
4 Results and Discussions XXIV-XXV
XXVI-XXVII
5 Conclusion and Future enhancement
XXVIII
6 References
1
Chapter 1
INTRODUCTION
In today's fast-paced urban environments, the ability to quickly and efficiently find nearby
businesses is essential for both residents and visitors. Whether one is searching for a
restaurant, retail store, or professional service, having a reliable system that can accurately
locate these businesses can significantly enhance convenience and save valuable time. This
report examines the development of a sophisticated system that leverages the power of the
Google Maps API in conjunction with Dijkstra's algorithm to optimize the search for nearby
businesses.
The Google Maps API is a versatile tool that provides extensive geographic data, including
detailed information on business locations, road networks, and real-time traffic conditions.
This wealth of data serves as the foundation for building a robust search system. On the other
hand, Dijkstra's algorithm is a well-established computational method renowned for its ability
to determine the shortest paths in weighted graphs, making it an ideal choice for route
optimization tasks.By combining the comprehensive geographic capabilities of the Google
Maps API with the pathfinding efficiency of Dijkstra's algorithm, the developed system aims
to provide users with accurate, real-time route suggestions to nearby businesses. This
integration not only improves the speed and precision of business searches but also enhances
the overall user experience by offering optimal route recommendations tailored to individual
preferences and current traffic conditions.
This report provides an in-depth look at the methodology, implementation, and performance
evaluation of the system, highlighting its effectiveness in various urban scenarios.
Additionally, it addresses potential challenges, such as managing large datasets and handling
dynamic traffic updates, and proposes solutions to these issues. Through this study, we
demonstrate the potential of combining advanced algorithms with comprehensive geolocation
APIs to solve practical problems in urban navigation and local business discovery, ultimately
contributing to more efficient and user-friendly urban living.
2
The domain of this study focuses on urban navigation and local business discovery,
leveraging technology to improve the efficiency of finding nearby businesses in city
environments. Urban navigation involves using tools like GPS, mapping applications, and
real-time traffic updates to navigate city landscapes efficiently. Local business discovery aims
to help users locate services such as restaurants, stores, and healthcare providers within a
specific area, considering factors like distance and user preferences.Combining the Google
Maps API with Dijkstra's algorithm enables the development of systems that efficiently locate
nearby businesses and provide optimal routes to reach them. This integration is particularly
valuable in complex urban settings, enhancing user experience with accurate, real-time route
suggestions tailored to individual needs and current traffic conditions. This domain
significantly contributes to improving urban living and connectivity.
1.2 Scope
The scope of this project encompasses the development and implementation of a system that
integrates the Google Maps API with Dijkstra's algorithm to optimize the search for nearby
businesses in urban environments. The system will provide users with real-time information
on local services such as restaurants, retail stores, and healthcare providers, and offer the most
efficient routes to these businesses based on user-defined criteria like travel distance or time.
The project will include the following key components:
1. Data Retrieval: Accessing and retrieving geographic data, business information, and
real-time traffic updates using the Google Maps API.
2. Graph Construction: Building a weighted graph from the retrieved data, where nodes
represent locations and edges represent roads with weights corresponding to travel
distances or times.
3. Pathfinding Algorithm: Implementing Dijkstra's algorithm to compute the shortest
paths from the user's location to various business destinations.
3
Objectives
1. Optimize Business Search: Develop a system that efficiently searches for nearby
businesses based on user-defined criteria such as shortest distance or travel time.
2. Accurate Route Suggestions: Integrate Dijkstra's algorithm with the Google Maps API
to provide precise and efficient route recommendations from the user's location to
selected businesses.
3. Real-Time Updates: Ensure the system utilizes real-time traffic data to dynamically
update route suggestions and maintain accuracy under varying traffic conditions.
4. User-Friendly Interface: Create an intuitive and easy-to-use interface that allows users
to quickly input their location and preferences and receive business recommendations
and routes.
5. Enhance User Experience: Improve overall user experience by providing a seamless
and efficient method for discovering local businesses and navigating urban
environments.
By achieving these objectives, the project aims to create a practical tool that significantly
enhances the convenience and efficiency of urban navigation and local business discovery,
ultimately contributing to better urban living experiences.
4
Chapter 2
DESIGN ARCHITECTURE
● Input Form: Allows users to enter their current location and select the type of business
they are looking for.
● Map Display: Embeds Google Maps to show the user's location and nearby
businesses.
● Results List: Displays a list of nearby businesses with their details (e.g., name,
address, distance).
Frontend Logic:
● Handles User Input: Captures and validates user input from the form.
● Displays Results: Updates the map and results list based on data received from the
backend.
Backend Logic:
● API Request Handler: Sends requests to the Google Maps API to fetch data about
nearby businesses.
● Data Processor: Parses the JSON data received from the Google Maps API.
● Dijkstra's Algorithm: Calculates the shortest paths from the user's location to each
nearby business.
● Provides Data: Returns data about nearby businesses based on the user's location and
search parameters.
5
Database:
● Location Data: Stores geospatial data of the user's location and businesses.
● Business Details: Stores details about the businesses (e.g., name, address, type).
● User Queries: Stores user search queries for analytics and improvement purposes.
The design architecture for the system to find nearby businesses using the Google Maps API
and Dijkstra's algorithm is divided into three key layers:
Components:
6
● Google Maps Places API: Retrieves business details (names, addresses, coordinates)
based on user location and radius.
● Google Maps Distance Matrix API: Calculates travel distances between businesses to
use as edge weights.
Process:
2. Processing Layer
Components:
● Graph Construction:
○ Nodes: Businesses with attributes.
○ Edges: Weighted by distances.
● Dijkstra’s Algorithm: Computes shortest paths from the start business to others.
Process:
Components:
Process:
Data Flow
This architecture ensures effective data handling, processing, and presentation for finding
nearby businesses.
2.3 Methodology
To develop a Python-based system that utilizes the Google Maps API to identify and locate
nearby businesses and applies Dijkstra's algorithm to determine the shortest paths between a
user's location and these businesses. The scope includes fetching business data, constructing a
graph of business locations, and calculating optimal routes.
1. Data Collection:
● Google Maps API Setup: Obtain an API key from Google Cloud to access Google
Maps services. This key is necessary for making API requests to fetch geographic and
business data.
● Fetching Nearby Places: Use the places_nearby method from the Google Maps Places
API to retrieve businesses within a specified radius from a given location. This
method provides information such as business names, locations (latitude and
longitude), and place IDs.
● Node Representation: Each business is represented as a node in the graph. Nodes are
created using business place IDs and their geographic coordinates (latitude and
longitude).
● Edge Creation: Calculate the distance between each pair of nodes (businesses) using
8
the Google Maps Distance Matrix API. Each distance is used as the weight of the
edge connecting the corresponding nodes. This step involves querying the Distance
Matrix API to get travel distances or times between businesses.
4. Results Interpretation:
● Distance Calculation: After running Dijkstra's algorithm, collect and sort the distances
from the start node to each other node (business) in ascending order. This allows for
the identification of the shortest paths to various businesses.
● Output: Display the list of nearby businesses along with their distances from the start
node. This information is useful for determining which businesses are closest and how
far they are from the starting point.
5. Visualization (Optional):
● Testing: Validate the functionality by running the code with different user locations
and radius values. Ensure that the system accurately fetches businesses and computes
distances.
9
● Error Handling: Implement error handling to manage potential issues such as API
request failures or invalid responses.
Chapter 3
IMPLEMENTATION
Source Code 3.1:
app.py
from flask import Flask, request, jsonify, render_template
import heapq
import requests
app = Flask(__name__)
GOOGLE_MAPS_API_KEY = 'AIzaSyAzCj1kiAPKjl3pcmqcKSQboyN78g_14OU'
def get_place_location(place_name):
url =
f"https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input={place_name}&
inputtype=textquery&fields=geometry&key={GOOGLE_MAPS_API_KEY}"
response = requests.get(url)
place_data = response.json()
if place_data['status'] == 'OK' and place_data['candidates']:
location = place_data['candidates'][0]['geometry']['location']
return location['lat'], location['lng']
return None, None
while min_heap:
current_distance, current_index = heapq.heappop(min_heap)
if visited[current_index]:
continue
visited[current_index] = True
return distances
@app.route('/')
def index():
return render_template('index.html')
@app.route('/nearest-businesses', methods=['POST'])
12
def nearest_businesses():
data = request.json
origin = data['origin']
destinations = data['destinations']
valid_destinations = []
destination_coords = []
for destination in destinations:
lat, lng = get_place_location(destination)
if lat is not None and lng is not None:
valid_destinations.append(destination)
destination_coords.append(f"{lat},{lng}")
else:
print(f"Destination '{destination}' could not be found.")
if not valid_destinations:
return jsonify({'error': 'No valid destinations found.'}), 400
for i in range(len(rows)):
elements = rows[i].get('elements', [])
for j in range(len(elements)):
if elements[j].get('status') == 'OK':
dist_matrix[i][j] = elements[j].get('distance', {}).get('value', float('inf'))
else:
dist_matrix[i][j] = float('inf')
distances = dijkstra(dist_matrix, 0)
print("Dijkstra Distances:", distances) # Debug: Print distances calculated by Dijkstra
result = [{
'destination': valid_destinations[index],
'distance': distance if distance is not None else 'unreachable',
'lat': destination_coords[index].split(',')[0],
'lng': destination_coords[index].split(',')[1]
14
return jsonify({
'origin': {'lat': origin_lat, 'lng': origin_lng},
'destinations': result
})
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<title>Nearest Among Places</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAzCj1kiAPKjl3pcmqcKSQboyN
78g_14OU&callback=initMap" async defer></script>
<style>
#map {
height: 500px;
width: 100%;
}
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
15
h1 {
text-align: center;
margin: 20px 0;
}
form {
display: flex;
flex-direction: column;
align-items: center;
margin-bottom: 20px;
}
input {
margin: 10px;
padding: 10px;
width: 300px;
}
#results {
list-style: none;
padding: 0;
}
#results li {
margin: 5px 0;
}
</style>
</head>
<body>
<h1>Find Nearest Among Places</h1>
<form id="search-form">
<label for="origin">Origin:</label>
<input type="text" id="origin" name="origin" required><br><br>
16
<script>
let map;
let markers = [];
let polylines = [];
let labels = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 0, lng: 0 },
zoom: 12
});
}
function clearMap() {
markers.forEach(marker => marker.setMap(null));
polylines.forEach(polyline => polyline.setMap(null));
labels.forEach(label => label.setMap(null));
markers = [];
polylines = [];
labels = [];
}
17
$(document).ready(function() {
$('#search-form').on('submit', function(event) {
event.preventDefault();
$.ajax({
url: '/nearest-businesses',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ origin: origin, destinations: destinations }),
success: function(response) {
if (!map) {
console.error('Map not initialized.');
return;
}
clearMap();
$('#results').empty();
}));
response.destinations.forEach(function(result) {
$('#results').append(`<li>${result.destination}: ${result.distance}
meters</li>`);
const destinationLatLng = new google.maps.LatLng(result.lat, result.lng);
const midPoint = {
lat: (lastLatLng.lat() + destinationLatLng.lat()) / 2,
lng: (lastLatLng.lng() + destinationLatLng.lng()) / 2
};
1. Backend Implementation
Technologies Used:
● Flask: A lightweight web framework that facilitates the creation of the server-side
application. Flask is chosen for its simplicity and flexibility, making it ideal for
developing RESTful APIs and handling HTTP requests with minimal overhead.
● Requests: A popular Python library used for making HTTP requests to the Google
Maps API. It simplifies the process of sending requests and handling responses,
making integration with external services straightforward.
● Heapq: A Python module for implementing priority queues, which is crucial for
efficiently executing Dijkstra’s algorithm. It allows for quick retrieval of the next node
with the smallest distance, essential for finding the shortest paths in a graph.
Core Functions:
1. get_distance_matrix(origins, destinations)
● Purpose: This function is responsible for retrieving the distances between the origin
point and multiple destination points using the Google Maps Distance Matrix API. It
ensures that the distances are calculated accurately for each pair of origin and
destination.
● Usage: The function sends an HTTP GET request to the Distance Matrix API,
providing the origins and destinations as parameters. The API response, which is in
JSON format, includes distance data that is then processed and used for further
calculations.
2. dijkstra(dist_matrix, start_index)
● Purpose: Computes the shortest paths from a specified start node to all other nodes
within the graph. This function uses Dijkstra’s algorithm to determine the minimum
distances from the start node to each of the destination nodes.
● Algorithm: The function utilizes a priority queue, implemented via the heapq
module, to efficiently manage and retrieve the node with the smallest distance. It
iteratively updates the distances as it traverses the graph, ensuring that the shortest
paths are found.
3. get_geocode(address)
21
● Purpose: Converts a physical address into latitude and longitude coordinates using
the Google Maps Geocoding API. This geocoding process is crucial for accurately
placing locations on the map.
● Usage: The function sends an HTTP GET request to the Geocoding API with the
provided address. The API responds with the geocoding results, which include
latitude and longitude values that are essential for mapping and distance calculations.
1.API Endpoints:
● Description: Renders the frontend HTML page that allows users to interact with the
application. It serves as the entry point for users accessing the web application.
2.nearest-businesses:
● Description: Processes POST requests to find the nearest businesses based on user
input. This endpoint handles the logic for fetching distance data, computing the
shortest paths using Dijkstra’s algorithm, and returning the geocoded locations along
with their distances. It is the core of the functionality, integrating various services and
processing user requests to provide accurate results.
2. Frontend Implementation
Technologies Used:
● HTML/CSS: Utilized for structuring and styling the web page. HTML provides the
basic structure, while CSS ensures that the page is visually appealing and
user-friendly.
● JavaScript/jQuery: Handles user interactions and AJAX requests. JavaScript and
jQuery are used for dynamically updating the page content based on user actions and
server responses, enhancing the interactivity of the web application.
● Google Maps JavaScript API: Provides functionality to display the map, place
markers, and draw polylines between locations. This API is integral to visualizing the
data and interactions on the map.
Core Functions:
1. Form Handling
● Purpose: Collects user input for the origin and destinations. The form submission
triggers an AJAX request to the backend, which processes the data and retrieves the
nearest businesses.
● Process: The user fills out the form with the origin and destination details, which are
then submitted via an AJAX request. Upon receiving the response from the backend,
the page is updated to display the results.
2. Map Initialization
● Purpose: Sets up the Google Map on the web page, ensuring that it is ready to display
locations and routes.
22
● Function: The Google Maps API is used to initialize the map with default settings
such as center and zoom level. Markers for the origin and destination points are
placed on the map, providing visual cues for the locations.
3. Results Display
● Purpose: Displays a list of the nearest businesses and their corresponding distances
on the web page.
● Function: The results are dynamically updated in an HTML list, and markers for each
destination are placed on the map. This allows users to see both the textual list of
results and their locations on the map. Additionally, polylines are drawn to indicate
the paths between the origin and the destinations, with labels showing the distance
order.
● Purpose: Provides users with feedback in case of errors or issues with the API
requests or data processing.
● Function: Error messages are displayed to the user if there are problems with the API
requests or if no valid destinations are found. This ensures that users are informed of
any issues and can take corrective actions.
23
3.3 Output:
fig 3.3.1 Result showing nearest to farthest paths from origin (instead of businesses we
have shown places for more clarity)
24
Chapter 4
The implementation of the system for locating nearby businesses using the Google Maps API
and Dijkstra’s algorithm yielded positive and practical outcomes. The system successfully
utilized the Google Maps API to gather a list of businesses within a specified radius from a
given location. Each business was represented as a node in a graph, with the distances
between them serving as edge weights. This setup allowed Dijkstra’s algorithm to compute
the shortest paths from a designated starting business to all other businesses in the vicinity.
The output was a ranked list of businesses ordered by their proximity to the starting point,
providing a clear and actionable overview of nearby options.
The accuracy of the distances computed and the efficiency of the algorithm in processing the
data were commendable. For example, businesses that were closer to the starting point were
correctly identified as such, and the distance measurements aligned closely with real-world
expectations. The system demonstrated reliable performance in providing recommendations
based on proximity, which is critical for applications such as local search and navigation.
Discussion-
The results of the system highlighted several strengths as well as areas for improvement. One
notable strength was the accurate retrieval and representation of nearby businesses, supported
by real-time data from the Google Maps API. This facilitated effective use of Dijkstra’s
algorithm to determine shortest paths and provide practical business recommendations. The
algorithm performed efficiently with the data provided, generating accurate results in a timely
manner.
However, the methodology of connecting all nodes in the graph might not always reflect
real-world travel scenarios. In practical terms, businesses are not always directly accessible
from one another, and the assumption of direct connections could lead to inaccuracies. To
address this, future iterations of the system could benefit from incorporating real-time traffic
25
data, which would allow for more accurate distance calculations and reflect actual travel
conditions. Additionally, refining the graph to connect only relevant or nearby nodes would
improve both accuracy and performance, especially as the dataset grows larger.
While the system’s user interface provided clear and intuitive results, there is potential to
enhance the user experience further. Features such as customizable search filters (e.g.,
business ratings or types) and real-time navigation capabilities could add significant value.
These enhancements would provide users with more tailored and practical information,
improving overall satisfaction.
In summary, while the integration of the Google Maps API with Dijkstra’s algorithm proved
effective in delivering accurate and efficient nearby business recommendations, there are
opportunities for refinement. Addressing the limitations of node connectivity, incorporating
real-time data, and enhancing user features will contribute to a more robust and scalable
solution.
26
By addressing these areas for improvement, the system can be refined to offer more accurate,
user-friendly, and scalable solutions for locating nearby businesses. The incorporation of
advanced features and optimizations will further enhance its practical utility and user
satisfaction.
28
REFERENCES
GeeksforGeeks
Khan Academy