简体   繁体   中英

How to show Azure Cosmos DB data using C# .net MVC framework on google marker map?

I am trying to achieve google marker map for data from Cosmos Db using C# .net MVC framework. I am not able to pass data to google maps javascript. I have added my code for reference. Please help. Thanks

I am new c# developer. I am using Azure Cosmos db database for application.I tried different method to pass data to Google maps script but it not working.

Model:

public class Device
{
  [JsonProperty(PropertyName = "id")]
  public string Id { get; set; }

  [JsonProperty(PropertyName = "Name")]
  public string Name { get; set; }

  [JsonProperty(PropertyName = "Address")]
  public string Address { get; set; }

  [JsonProperty(PropertyName = "Lat")]
  public double Lat { get; set; }

  [JsonProperty(PropertyName = "Long")]
  public double Long { get; set; }
}

Controller:

public class DeviceController : Controller
{
  public async Task<ActionResult> MapAsync() 
  {
    var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
      return View();
}

View:

@model IEnumerable<WebApplication1.Models.Device>

<script>
@foreach (var item in Model)
{
  Html.Raw(" var features = [{position: new google.maps.LatLng(" + item.Lat + "," + item.Long + "), type: 'parking' },];");
}
</script>

<script>
var map;

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 16,
        center: new google.maps.LatLng(-33.91722, 151.23064),
        mapTypeId: 'roadmap'
    });

    var iconBase = 'http://localhost:20557/Content/Images/';
    var icons = {
        parking: {
            icon: iconBase + 'trafficlight-green.png'
        }
    };



    // Create markers.
    features.forEach(function (feature) {
        var marker = new google.maps.Marker({
            position: feature.position,
            icon: icons[feature.type].icon,
            map: map
        });
    });
}
</script>

above is the last thing I tried still no help. Please let me know if you want any more information to help me. New to posting questions here.

Please refer working sample created on Net Core MVC in here Take a look at index action in Home controller and index.cshtml view.

In your code at first you need to pass Modal to view. Your Code:

 var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
  return View();

Should pass modal to view like below.

 var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
  return View(items);

.Creation of features array in view is incorrect

@foreach (var item in Model)

{ Html.Raw(" var features = [{position: new google.maps.LatLng(" + item.Lat + "," + item.Long + "), type: 'parking' },];"); }

Just create Javascript array from c# list in View like

  var locationArray = @Html.Raw(Json.Serialize(ViewBag.Locations));

So Update script section in view can be like this. Please refer github link for actual working sample

 var map;
    function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        center: {lat: -34.397, lng: 150.644},
        zoom: 8
    });
    }

    $(document).ready(function() {
    initMap();

    var locationArray = @Html.Raw(Json.Serialize(ViewBag.Locations));

    var newArray = locationArray.map((value)  => { 
        return  {
            position: new google.maps.LatLng(value.lat, value.lon),
            type:'parking' 
        }
    });
      // Create markers.
    newArray.forEach(function (feature) {
        var marker = new google.maps.Marker({
            position: feature.position,
            map: map
        });
    });

    });

Note: In my sample soultion I have passed list of locations to view using view bag. you can use passing as Modal. Out put will be like this 出来的样品

Edit: To populate javascript array from list can follow this way also.

  var locationArray = [];

    @foreach (var item in ViewBag.Locations)
    {
         @:locationArray.push("{lat:@item.lat, lon:@item.lon}");
    }

Thanks all for your help @Erik and @Jeevan your suggestion helped a lot.for anyone else trying to achieve same thing here is viewcode:

function initialize() {
    // Enable the visual refresh
    google.maps.visualRefresh = true;

    var mapOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 10
    }
    var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

    // ADD FULL SCREEN BUTTON
   // map.controls[google.maps.ControlPosition.TOP_RIGHT].push(
    //    FullScreenControl(map)
 //   );

    google.maps.event.addListener(map, "idle", function () {
        $("#map-loader-container").css("background", "none");
    });
    // get all signs and create a json object from the array
    //  var signs = '.json_encode($this->_data['items']).';

    // creates the var to hold all corrdenates so we can center the map around them later
    var myLatLngBounds = new google.maps.LatLngBounds();

    // create the container for the Info Window
    var infoWindow = new google.maps.InfoWindow({
        content: "",
        maxWidth: 500,
        minWidth: 400
    });

    // create the marker
                  @foreach (var item in Model)
                       {<text>
    var myLatLng = new google.maps.LatLng(@Html.DisplayFor(modelItem => item.Lat), @Html.DisplayFor(modelItem => item.Long)); // set the coordenates
    myLatLngBounds.extend(myLatLng); // add the marker to be centered in the map 
    var marker = new google.maps.Marker({
        position: new google.maps.LatLng(@Html.DisplayFor(modelItem => item.Lat), @Html.DisplayFor(modelItem => item.Long)),
        map: map,
        icon: "/Content/Images/green.png",
        //optimized: false,
        title: "@Html.DisplayFor(modelItem => item.Name)",
        html:<h4> @Html.DisplayFor(modelItem => item.Name) </h4>
            <div id="bodyContent">
            <p> @Html.DisplayFor(modelItem => item.Address)<br /><a href="@Html.DisplayFor(modelItem => item.DeviceId)"></a></p>
            </div>
    });

    google.maps.event.addListener(marker, "click", function () {
        infoWindow.setContent(this.html);
        infoWindow.open(map, this);
    });
    </text>
                    }

    // centers the map around the coordinates
    map.setCenter(myLatLngBounds.getCenter());
    map.fitBounds(myLatLngBounds);
    //console.info(map.getZoom());
    //map.setZoom(1);

    var listener = google.maps.event.addListener(map, "idle", function () {
        if (map.getZoom() > 15) map.setZoom(15);
        google.maps.event.removeListener(listener);
    });
}

            // Asynchronously Loading the API
            function loadScript() {
                var script = document.createElement("script");
                script.type = "text/javascript";
                script.src = "https://maps.googleapis.com/maps/api/js?key=xxxxxx0&callback=initialize";
                document.body.appendChild(script);
            }

            // Load the API after page finish rendering
            window.onload = loadScript;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM