Как отобразить данные Azure Cosmos DB с помощью C # .net MVC framework на карте маркеров Google? - PullRequest
0 голосов
/ 08 февраля 2019

Я пытаюсь получить карту маркеров Google для данных из Cosmos Db, используя C # .net MVC framework.Я не могу передать данные в Google Maps Javascript.Я добавил свой код для справки.Пожалуйста помоги.Спасибо

Я новый разработчик C #.Я использую базу данных Azure Cosmos db для приложения. Я пробовал другой способ передачи данных в скрипт Google maps, но он не работает.

Модель:

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; }
}

Контроллер:

public class DeviceController : Controller
{
  public async Task<ActionResult> MapAsync() 
  {
    var items = await DocumentDBRepository<Device>.GetDevicemapAsync(d => d.Id != null);
      return 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>

выше - последнее, что я попробовал, но до сих пор не помог.Пожалуйста, дайте мне знать, если вы хотите больше информации, чтобы помочь мне.Новое в размещении вопросов здесь.

Ответы [ 2 ]

0 голосов
/ 11 февраля 2019

Спасибо всем за помощь, @Erik и @Jeevan, ваше предложение очень помогло. Для тех, кто пытается достичь того же, здесь есть код:

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;
0 голосов
/ 08 февраля 2019

Пожалуйста, ознакомьтесь с рабочим примером, созданным в Net Core MVC, в здесь Посмотрите на действие index в контроллере Home и представление index.cshtml.

В вашем коде сначала вам нужно пройти Модал для просмотра.Ваш код:

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

Должен пройти модальный для просмотра, как показано ниже.

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

. Создание массива объектов в представлении неверно

@foreach (var item in Model)

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

Просто создайте массив Javascript из списка c # в View как

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

Так что раздел Обновление скрипта в представлении может выглядеть следующим образом.Пожалуйста, обратитесь к ссылке на GitHub для фактического рабочего образца

 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
        });
    });

    });

Примечание: В моем примере я передал список мест для просмотра, используя пакет просмотра.Вы можете использовать передачу как модальный.Выход будет выглядеть следующим образом: Out put of sample

Редактировать: заполнять массив javascript из списка можно также следующим образом.

  var locationArray = [];

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