What do we want to achieve,
- Create a Google Maps AutoComplete dropdown.
- Save those address details into our database Server (here, I am using SQL Server).
- Retrieve those map details into the browser, create and place markers on the map.
- Navigate between markers on mouse click.
Note
Before creating the project, I will show you how to get API key for Google Maps API.
Step 1.0
Create a Google Maps API from Google console application
It will take some time to create the project.
The credentials have been created. Now, create an MVC project.
Step 1.1
Create an MVC project and name it as GoogleMapTutor.
Step 2
Create Place.cs and MapDbContext.cs files into "Models" folder.
Add the code into MapDbContext.cs file.
- using System;
- using System.Collections.Generic;
- using System.Data.Entity;
- using System.Linq;
- using System.Web;
- namespace GoogleMapTutor.Models {
- public class MapDbContext: DbContext {
- public MapDbContext(): base("GoogleMapConnString") {
- Database.SetInitializer < MapDbContext > (new DropCreateDatabaseIfModelChanges < MapDbContext > ());
- }
- public DbSet < Place > places {
- get;
- set;
- }
- }
- }
The code given above is to generate a database, using Entity Framework Code-First Approach.
Step 3
Add the connection string into Web.config file.
Step 4
Add a Controller into Controllers > PlacesController and paste the code given below.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using GoogleMapTutor.Models;
- namespace GoogleMapTutor.Controllers {
- public class PlacesController: Controller {}
- }
Add 4 action methods given below into the Controller class.
- MapDbContext db = new MapDbContext();
- public ActionResult Index() {
-
- var items = new List < SelectListItem > ();
- var groups = db.places.Select(x => new SelectListItem {
- Text = x.PlaceGroupId, Value = x.PlaceGroupId
- }).Distinct().ToList();
- if (groups != null && groups.Count > 0) {
- groups[0].Selected = true;
- }
- return View(groups);
- }
- [HttpGet]
- public ActionResult Add() {
- return View();
- }
- [HttpPost]
- public ActionResult Add(List < Place > places) {
- places.ForEach(x => x.Id = Guid.NewGuid());
- db.places.AddRange(places);
- var result = db.SaveChanges();
- if (result > 0) {
- return Json(new {
- result = "Redirect", url = Url.Action("Index", "Places")
- });
- }
- return Json(new {
- result = "InvalidLogin"
- }, JsonRequestBehavior.AllowGet);
- }
- [HttpGet]
- public JsonResult GetLocationsByGroupId(string groupid) {
- var locations = db.places.Where(x => x.PlaceGroupId == groupid).ToList();
- return Json(locations, JsonRequestBehavior.AllowGet);
- }
The first is Method Index() which returns List<SelectListItem>() for dropdown.
The last method is to get all the places, which are based on its GroupId. This function will return JSON data.
Step 5
Create two files “Add.cshtml” and “Index.cshtml” into Into Views>Places folder (Create Places folder, if it does not exist).
Note
Please make sure that in Layout.cshtml page, jQuery and Bootstrap are referred.
Step 6
Open “Add.cshtml” file
Step 7
Create an app folder into Scripts folder and add add.js file.
- In JS given above, I have created one Controller for our View, one factory to communicate with our back-end Server, and one directive for Google Maps auto-complete.
- The directive will simply create the auto-complete dropdown into our HTML page.
Step 8
Run the Application
Step 9
Index.cshtml file,
Remove everything and paste the code given below into index.cshtml file in Places folder.
Replace the credentials used for the Application and paste your own credentials into Google API script tag given below.
Step 10
Add “index.js” and “google-map-dir.js” files into Scripts>app and Scripts>app>Directives(create Directives folder, if it does not exist) folders respectively.
Step 11
Paste the code given below into index.js file.
- angular.module('GoogleMapApp', ['googleMapDirectiveApp']).controller('GoogleMapAppController', function($scope, GoogleMapAppFactory) {
- $scope.init = function() {
- GoogleMapAppFactory.GetLocations($scope.groupId).then(function(response) {
- $scope.locationList = response.data;
- if ($scope.locationList && $scope.locationList.length) {
- $scope.GoToThisLocation($scope.locationList[0].Latitude, $scope.locationList[0].Longitude);
- }
- }, function(error) {
- alert("error!!!");
- })
- }
- $scope.selectedLocation = {
- lat: 23,
- lon: 79
- };
- $scope.GoToThisLocation = function(lat, lon) {
- if ($scope.selectedLocation.lat != lat || $scope.selectedLocation.lon != lon) {
- $scope.selectedLocation = {
- lat: lat,
- lon: lon
- };
- if (!$scope.$$phase) {
- $scope.$apply("selectedLocation");
- }
- }
- }
-
- }).factory("GoogleMapAppFactory", function($http) {
- var fac = {}
- fac.GetLocations = function(locationGroupId) {
- return $http.get('/Places/GetLocationsByGroupId?groupid=' + locationGroupId)
- }
- return fac;
- })
$scope.GoToThisLocation() function will be called when we change (select) a particular place from the place list.
Step 12
Add the code given below into google-map-dir.js file.
- angular.module("googleMapDirectiveApp", []).directive('googleMapDir', function() {
- return {
- restrict: "EA",
- replace: true,
- template: "<div></div>",
- scope: {
- center: '=',
- markers: '=',
- width: "@",
- height: "@"
- },
- link: function(scope, element, attribute) {
-
- var map;
- scope.$watch('center', function() {
-
- if (map && scope.center && scope.markers) {
- map.setCenter(getLocation(scope.center))
- }
- })
- scope.$watch('markers', function() {
-
- if (scope.markers) {
- updateControl();
- }
- })
-
- function updateControl() {
-
- var options = {
- center: new google.maps.LatLng(23, 79),
- zoom: 15,
- mapTypeId: "roadmap"
- }
- if (scope.center.lat && scope.center.lon) {
- options.center = getLocation(scope.center)
- } else {
- return
- }
- map = new google.maps.Map(element[0], options);
- updateMarkers();
- }
-
- function updateMarkers() {
-
-
- currentMarkers = [];
- var markers = scope.markers;
- if (angular.isString(markers)) markers = scope.$eval(scope.markers);
- for (var i = 0; i < markers.length; i++) {
- var m = markers[i];
- var loc = new google.maps.LatLng(m.Latitude, m.Longitude);
- var mm = new google.maps.Marker({
- position: loc,
- map: map,
- title: m.FullAddress
- });
- currentMarkers.push(mm);
- }
- }
-
- function getLocation(location) {
- if (location == null) {
- return new google.maps.LatLng(23, 79);
- }
- if (angular.isString(location)) {
- location = scope.$eval(location);
- }
- return new google.maps.LatLng(location.lat, location.lon)
- }
- }
- }
- })
Step 13
Run the Application.
Great. You have created Google Maps auto-complete with multiple pointers with navigation.