- By Musawar Hussain 23-Jul-2024
- 205
How to display bissiness Location in Google map
Our Store Controller Code:
using KFSOnlineShop.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace KFSOnlineShop.WebUI.Controllers
{
public class OurStoresController : Controller
{
//OurStores
public ActionResult Index()
{
var stores=ItechnocratHealthRepoistoryV1.GetStores();
return View(stores);
}
public ActionResult Search(double latitude, double longitude, double radius = 20)
{
var stores = ItechnocratHealthRepoistoryV1.GetStores();
var nearbyStores = stores.Where(store =>
GetDistance(latitude, longitude, store.Latitude, store.Longitude) <= radius).ToList();
return View("Index", nearbyStores);
}
private double GetDistance(double lat1, double lon1, double lat2, double lon2)
{
// Haversine formula for distance calculation
var R = 6371; // Radius of the Earth in kilometers
var dLat = ToRadians(lat2 - lat1);
var dLon = ToRadians(lon2 - lon1);
var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
Math.Cos(ToRadians(lat1)) * Math.Cos(ToRadians(lat2)) *
Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
return R * c;
}
private double ToRadians(double angle)
{
return angle * (Math.PI / 180);
}
}
}
Action Methods Code:
Index:
@using Newtonsoft.Json
@{
ViewBag.Title = "Store Locator";
Layout = "~/Views/Shared/_KFSLayout.cshtml";
}
<div class="page-heading">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="page-title">
<h2>
Store Locator
</h2>
</div>
</div>
<!--col-xs-12-->
</div>
<!--row-->
</div>
<!--container-->
</div>
@model IEnumerable<KFSOnlineShop.Common.Store>
<div class="container">
<div class="row" style="padding:5px !important;">
<div class="col-md-12">
<input type="text" id="locationSearch" class="form-control" placeholder="Enter location" style="width:300px !important" />
<label for="radius" class="mt-2">Radius:</label>
<input type="number" id="radius" class="form-control" value="20" style="width:50px !important" />
<button id="searchButton" class="btn btn-primary mt-2">Search</button>
</div>
</div>
<div class="row">
<div class="col-md-6" id="listView">
@foreach (var store in Model)
{
<div class="store-item">
<h3>@store.Name</h3>
<p>@store.Address</p>
</div>
}
</div>
<div class="col-md-6" id="mapView" style="height: 500px;"></div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/leaflet@1.7.1/dist/leaflet.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
<script>
$(document).ready(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
// Reverse geocoding to get the address (using a geocoding service, e.g., OpenStreetMap's Nominatim)
$.get(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}`, function (data) {
$('#locationSearch').val(data.display_name);
});
// Initialize the map with user's location
initializeMap(latitude, longitude);
});
} else {
alert("Geolocation is not supported by this browser.");
}
$('#searchButton').click(function () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const radius = $('#radius').val();
window.location.href = `/OurStores/Search?latitude=${latitude}&longitude=${longitude}&radius=${radius}`;
});
} else {
alert("Geolocation is not supported by this browser.");
}
});
function initializeMap(lat = 0, lon = 0) {
var map = L.map('mapView').setView([lat, lon], 13);
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
}).addTo(map);
var stores = @Html.Raw(JsonConvert.SerializeObject(Model));
stores.forEach(function(store) {
L.marker([store.Latitude, store.Longitude]).addTo(map)
.bindPopup('<b>' + store.Name + '</b><br />' + store.Address);
});
}
initializeMap();
});
</script>
StoreLocator Controller Code:
using KFSOnlineShop.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace KFSOnlineShop.WebUI.Controllers
{
public class StoreLocatorController : Controller
{
// GET: StoreLocator
public ActionResult Index2()
{
var dd = ItechnocratHealthRepoistoryV1.GetStores();
return View(dd);
}
[HttpPost]
public ActionResult Search(string searchTerm, double? userLat, double? userLng, int radius)
{
var dd = ItechnocratHealthRepoistoryV1.GetStores();
// Determine user's location (if not provided, use a default location)
double latitude = userLat ?? 37.7749; // Default to San Francisco latitude
double longitude = userLng ?? -122.4194; // Default to San Francisco longitude
// Search for stores based on search term, location, and radius
// var stores = _storeRepository.SearchStores(searchTerm, latitude, longitude, radius);
// Return JSON result
return Json(dd);
}
//public JsonResult GetStores()
//{
// // Replace this with actual logic to fetch data from your backend
// var stores = new List<StoreViewModel>
// {
// new StoreViewModel { Name = "Business 1", Address = "3320 - 20TH AVENUE NE, UNIT 109, CALGARY, AB, T1Y 6E8, Canada", Latitude = 51.0734, Longitude = -113.9940 },
// new StoreViewModel { Name = "Business 2", Address = "813 - 11 Ave SW, Calgary, AB, T2R 0E6, Canada", Latitude = 51.0425, Longitude = -114.0837 }
// // Add more stores as needed
// };
// return Json(stores, JsonRequestBehavior.AllowGet);
//}
//public class StoreViewModel
//{
// public string Name { get; set; }
// public string Address { get; set; }
// public double Latitude { get; set; }
// public double Longitude { get; set; }
//}
public ActionResult Index()
{
return View();
}
public JsonResult GetStores()
{
var dd=ItechnocratHealthRepoistoryV1.GetStores();
// var stores = new List<Store>
//{
// new Store { Name = "Business 1", Address = "3320 - 20TH AVENUE NE, UNIT 109, CALGARY, AB, T1Y 6E8, Canada", Latitude = 51.0734, Longitude = -113.9940 },
// new Store { Name = "Business 2", Address = "813 - 11 Ave SW, Calgary, AB, T2R 0E6, Canada", Latitude = 51.0425, Longitude = -114.0837 }
//};
return Json(dd, JsonRequestBehavior.AllowGet);
}
}
}
Action Methods Codes (Views)
Index2:
@{
Layout = "~/Views/Shared/_KFSLayout.cshtml";
}
@model List<KFSOnlineShop.Common.Store>
<h2>Store Locator</h2>
<div id="storeLocator">
<!-- Search Form -->
<form id="searchForm">
<label for="searchTerm">Search by Name:</label>
<input type="text" id="searchTerm" name="searchTerm" />
<button type="submit">Search</button>
</form>
<!-- Map and List View Tabs -->
<ul class="nav nav-tabs" id="myTab" role="tablist">
<li class="nav-item">
<a class="nav-link active" id="list-tab" data-toggle="tab" href="#listView" role="tab" aria-controls="listView" aria-selected="true">List View</a>
</li>
<li class="nav-item">
<a class="nav-link" id="map-tab" data-toggle="tab" href="#mapView" role="tab" aria-controls="mapView" aria-selected="false">Map View</a>
</li>
</ul>
<!-- Tab Content -->
<div class="tab-content" id="myTabContent">
<!-- List View -->
<div class="tab-pane fade show active" id="listView" role="tabpanel" aria-labelledby="list-tab">
<div id="storeList">
<!-- List of Stores will be populated here dynamically -->
@foreach (var store in Model)
{
<div class="storeItem">
<h3>@store.Name</h3>
<p>@store.Address</p>
<!-- Add more store details as needed -->
</div>
}
</div>
</div>
<!-- Map View -->
<div class="tab-pane fade" id="mapView" role="tabpanel" aria-labelledby="map-tab">
<div id="map" style="height: 400px;"></div>
</div>
</div>
</div>
<script>
// JavaScript/JQuery for handling search form submission
$(function () {
$('#searchForm').submit(function (event) {
event.preventDefault();
var searchTerm = $('#searchTerm').val();
// Call server-side action to search stores
$.ajax({
url: '@Url.Action("Search", "StoreLocator")',
type: 'POST',
data: {
searchTerm: searchTerm
},
success: function (data) {
// Update store list or map markers based on search result (data)
console.log(data); // Log the response for debugging
},
error: function (error) {
console.error('Error searching stores:', error);
}
});
});
});
</script>
Index:
@{
ViewBag.Title = "Store Locator";
Layout = "~/Views/Shared/_KFSLayout.cshtml";
}
<div class="page-heading">
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="page-title">
<h2>
Store Locator
</h2>
</div>
</div>
<!--col-xs-12-->
</div>
<!--row-->
</div>
<!--container-->
</div>
@{
ViewBag.Title = "Store Locator";
}
<div class="container">
<p>
<h2>Looking for where you can find KFS Rx meals? </h2>
We're thrilled to partner with a growing list of retailers, and we get excited every time we add a new one to our list! <br />
<h2>Tip: Please contact the store directly for availability, as we don't have access to each store's inventory.</h2>
Know a great place that could benefit from offering KFS Rx meals? Send a message to your favorite stores and let them know they’re missing out! The more interest they hear from YOU, the more likely we'll be available there.
<br /> <br />
Interested in becoming a partner? Please email Info@kfsrxmeals.com for more information!
</p>
<h2>Store Locator</h2>
<div class="row">
<div class="col-md-6">
<input type="text" id="currentLocation" class="form-control" value="111 2845 23rd Street NE, Calgary, AB T2E 7A4, Canada" placeholder="Enter your address or zip code">
<button id="btnuseMylocation" class="btn" style="margin-top: 10px;">Use my Current location</button>
<button id="searchButton" class="btn" style="margin-top: 10px;">Search</button>
<ul id="storeList" class="list-group" style="margin-top: 20px;"></ul>
</div>
<div class="col-md-6">
<div id="map" style="height: 500px; width: 100%;"></div>
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBEJOYJXofxbt8c465EYXEJXvYSzXtCVkM&libraries=places"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
var map, geocoder, bounds, directionsService, directionsRenderer;
var markers = [];
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: 51.0447, lng: -114.0719 }, // Calgary coordinates
zoom: 12
});
geocoder = new google.maps.Geocoder();
bounds = new google.maps.LatLngBounds();
directionsService = new google.maps.DirectionsService();
directionsRenderer = new google.maps.DirectionsRenderer();
directionsRenderer.setMap(map);
loadStores();
}
function loadStores() {
$.ajax({
url: '/StoreLocator/GetStores',
method: 'GET',
success: function (data) {
data.forEach(function (store, index) {
var latLng = new google.maps.LatLng(store.Latitude, store.Longitude);
bounds.extend(latLng);
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: store.Name
});
markers.push(marker);
marker.addListener('click', function () {
var address = $('#currentLocation').val();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
var origin = results[0].geometry.location;
calculateAndDisplayRoute(directionsService, directionsRenderer, origin, latLng, store);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
});
$('#storeList').append('<li class="list-group-item" data-index="' + index + '">' + store.Name + '<br>' + store.Address + '</li>');
});
map.fitBounds(bounds);
$('#storeList').on('click', '.list-group-item', function () {
$('#storeList .list-group-item').removeClass('active');
$(this).addClass('active');
var index = $(this).data('index');
var marker = markers[index];
map.setCenter(marker.getPosition());
map.setZoom(15);
google.maps.event.trigger(marker, 'click');
});
}
});
}
//
$('#searchButton').click(function () {
var address = $('#currentLocation').val();
if (address.trim() !== '') {
geocodeAddress(geocoder, address);
} else {
alert('Please enter an address or location.');
}
});
$('#btnuseMylocation').click(function (e) {
e.preventDefault();
getCurrentLocation();
});
function getCurrentLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var geolocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
geocoder.geocode({ 'location': geolocation }, function (results, status) {
if (status === 'OK') {
if (results[0]) {
$('#currentLocation').val(results[0].formatted_address);
searchStores();
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}, function () {
handleLocationError(true);
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false);
}
}
function handleLocationError(browserHasGeolocation) {
var errorMessage = browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.';
alert(errorMessage);
}
function geocodeAddress(geocoder, address) {
geocoder.geocode({ 'address': address }, function (results, status) {
if (status === 'OK') {
var origin = results[0].geometry.location;
map.setCenter(origin);
$('#storeList').empty();
directionsRenderer.setMap(null); // Clear previous directions
searchStores();
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function searchStores() {
$.ajax({
url: '/StoreLocator/GetStores',
method: 'GET',
success: function (data) {
data.forEach(function (store, index) {
var destination = new google.maps.LatLng(store.Latitude, store.Longitude);
var marker = new google.maps.Marker({
position: destination,
map: map,
title: store.Name
});
markers.push(marker);
marker.addListener('click', function () {
var destination = new google.maps.LatLng(store.Latitude, store.Longitude);
infoWindow.setContent('<div><strong>' + store.Name + '</strong><br>' +
'Address: ' + store.Address + '</div>');
infoWindow.open(map, marker);
calculateAndDisplayRoute(directionsService, directionsRenderer, origin, destination, store);
});
$('#storeList').append('<li class="list-group-item" data-index="' + index + '">' + store.Name + '<br>' + store.Address + '</li>');
});
map.fitBounds(bounds);
$('#storeList').on('click', '.list-group-item', function () {
$('#storeList .list-group-item').removeClass('active');
$(this).addClass('active');
var index = $(this).data('index');
var marker = markers[index];
map.setCenter(marker.getPosition());
map.setZoom(15);
google.maps.event.trigger(marker, 'click');
});
}
});
}
function calculateAndDisplayRoute(directionsService, directionsRenderer, origin, destination, store) {
directionsService.route({
origin: origin,
destination: destination,
travelMode: google.maps.TravelMode.DRIVING
}, function (response, status) {
if (status === 'OK') {
directionsRenderer.setMap(map); // Display directions on map
directionsRenderer.setDirections(response);
var route = response.routes[0].legs[0];
$('#storeList').append('<li class="list-group-item">' + store.Name + '<br>' + store.Address + '<br>Distance: ' + route.distance.text + '<br>Duration: ' + route.duration.text + '</li>');
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
$(document).ready(function () {
initMap();
getCurrentLocation();
});
</script>