fetching data from address field of ASP.NET MVC 5 Views to google map api to show locations markers and infowindow to display short description

My name is Sid. I am currently a student very new to all technology but i love to learn things … here is a small problem i am going through… before i state the issue please dont judge me by language and knowledge i am new and still learning apologies in advance! :smiley:

Problem Statement I want to display the data from the db to views and further display that data on google maps and show markers and small infowindow on those marked locations on map. for doing that i have made a Simple MVC application using VS 2017 using db first i made a db called infoDb using default db of VC2017, now i used VS scaffolding feature to get model using code first from db design and now scaffolded controller with views… below are the code for views as :- This is the index view for controller called GeoCodeLocationsController as follows:-

@model IEnumerable<MapPractise.Models.GeoCodeLocation>

    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    #map {
        height: 500px;
        width: 800px;
### Index

@*<input id="pac-input"  class="controls" type="text" placeholder="Search Box">*@

<div id="map"></div>

    @Html.ActionLink("Create New", "Create", "Locations", new { @class = "btn btn-primary" })

<table class="table">
            @Html.DisplayNameFor(model => model.Name)
            @Html.DisplayNameFor(model => model.Description)
            @Html.DisplayNameFor(model => model.Address)

    @foreach (var item in Model)
        <tr class="coordinates">
                @Html.DisplayFor(modelItem => item.Name)
            <td class="description">
                @Html.DisplayFor(modelItem => item.Description)
            <td id="addressLoc" class="address">
                @Html.DisplayFor(modelItem => item.Address)
                @Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
                @Html.ActionLink("Details", "Details", new { id = item.Id }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.Id })


@section Scripts {
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_API&libraries=places&callback=initAutocomplete" async defer></script>
please to mind the name of js i have use google API still i saved in mapbox for sake of experimenting code haha! Below is the Java script i trying to manipulate

        function initAutocomplete()
    var map = new google.maps.Map(document.getElementById('map'), {
            center: {
            lat: 52.728616,
        lng: 6.4901
      zoom: 13,
      mapTypeId: 'roadmap'
    var markers = [];

    // Create the search boxs and link them to the UI elements.
            var searchBoxes = $(".address");
    for (var i = 0; i < searchBoxes.length; i++) {
      var searchBox = new google.maps.places.SearchBox(searchBoxes[i]);
      map.addListener('bounds_changed', function() {
      searchBox.addListener('places_changed', (function(i) {
        return function() {
            processSearch(i, this)

      function processSearch(uniqueId, searchBox)
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return ;

      // Clear out the old markers.
      markers[uniqueId].forEach(function(marker) {
        markers[uniqueId] = [];

        // For each place, get the icon, name and location.
        var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        if (!place.geometry) {
            console.log("Returned place contains no geometry");
        var icon = {
            url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)

      // Create a marker for each place.
      if (!markers[uniqueId]) markers.push([]);
        markers[uniqueId].push(new google.maps.Marker({
            map: map,
        icon: icon,
        title: place.name,
        position: place.geometry.location

        if (place.geometry.viewport) {
            // Only geocodes have viewport.
        } else {

below is the Layout view from shared folder:-

<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>

    @* This is for the mapbox map. *@
    <script src='https://api.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.js'></script>
    <link href='https://api.mapbox.com/mapbox-gl-js/v0.47.0/mapbox-gl.css' rel='stylesheet' />
    @*This is used for the Geocoding Mapbox API*@
    <script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.2.0/mapbox-gl-geocoder.min.js'>
    <link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-geocoder/v2.2.0/mapbox-gl-geocoder.css' type='text/css' />

    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                    <li>@Html.ActionLink("MapBoxGeoCoder", "MapBoxGeoCoder", "Home")</li>
                    <li>@Html.ActionLink("Location", "Index", "Locations")</li>
                    <li>@Html.ActionLink("ViewGeo Code","Index","GeoCodeLocations")</li>
    <div class="container body-content">
        <hr />

© @DateTime.Now.Year - My ASP.NET Application


    @RenderSection("scripts", required: false)

now please dont mind about the other mess navigation tab in the layout file i just want to show if i have loaded all the javascript and jquery properly or not ? and now after running the code below is screen shot of what outcome happened

alt text

Now below is the screenshot of what i want to show on map from the index view (displays the content from the db using simple CRUD function)

alt text

now what i expect to do:- what i expected was that the from index view of the gecodelocation folder i want the addresses created to be listed on the google maps as marker and show the as infowindow descriptions… but when i ran the code it just pulled of the addresses and misplaced them on top of the map please refer to the screenshot. now i am new to javascript so any comments will be expected but i would really appreciate to know how to achieve my required outcome and what is right code to be implemented below is screen shot of what i could do correctly but i could manage to do using mapbox and i did reverse geocodeing using lat and long field

alt text

now if you see this screen shot i have pulled the data from index view of different view from problem statement i created a simple CRUD app using VC2017 now i could manage to pull the data from and place it in the pop-up infowindow but if u see the table displays latitude and longitude and i pull the data from class field of div tag of those and i insert them into js it runs fine i have used mapbox for that example though but that for just sake of showing, i actually what to feed in address as query instead of latitude and longitude also i do know that google map api and mapbox both provide different api obviously i am not mixing up… as per problem statement i want o use google map api to get results from veiws

thanks a lot in advance please let me know if there is any thing more i can provide to get my question more clear… also i have tried google searching a lot for geocoding examples but that could not suffice my expected problem most of them are using PHP mysql etc. but its nothing to do with back ends problem… more over i think i am making error in pulling data from view and inserting in javascript to run google map api. if you run the code mention i am not geting any errors in console i am pretty sure i have made a logic mistake please help me to sort out this.

Gratefully thanks to all of you in advance cheers Sid

Why don’t you discuss such kind of thing on StackOverflow rather than discussing on Codechef?

hi soho_garg, i read about Codeshef, it is a indian originated website which help to cook good programs if posted this questing over here too as i expect any of experienced users to help me to solve the logic problem in same code or if necessary script new javascript for required outcome.
hope this answers your question.

This is an old question, but if someone stumbles upon this I would like to point, that you need to save lat/long values in database as decimal and then using lat long you can point markers.

When you are loading map, get lat long as JSON and then place it in Map.

Something like this

        url: '/home/GetMapMarker',
        type: 'GET',
        success: function (data) {
            //create a blank array
            var markers = [];
            //loop the list of addresses returned from Ajax request
            $.each(data, function (index, item) {
                //create a blank array of address
                var marker = {};

                //fill data
                marker["title"] = item.AddressName;
                marker["lat"] = item.Lat;
                marker["lng"] = item.Long;
                marker["description"] = item.Description;

                //push the current marker details in markers array
            //call Map function with all markers passed as list of arrays


Source: Showing Google Maps in ASP.NET MVC with Marker (Lat/Long data from database)