MVC 4 and the Google Maps API v3

I use Google Maps in my MVC 4 application. Extremely straightforward. However, I have a question regarding the best way to add multiple tokens dynamically. My users will search for a list of products for sale by calling the action method on the controller, and I want to show them the elements and the location of each on the map. I'm not sure how and how best to add markers dynamically to a map, which is all the JavaScript in the client. Essentially, I would like to be able to send all marker information from the MVC server code to the client, but I'm not sure if this can or should be done that way.

+6
source share
4 answers

In the project I'm working on now, we are dealing with this:

Let main ViewModel be called FooViewModel .

ViewModels:

 public class FooViewModel { // Your search results: public IEnumerable<FooWithLocationViewModel> Foos { get; set; } // Properties for your search filter: public decimal? MaxPrice { get; set; } public CityEnum? City { get; set; } ... } public class FooWithLocationViewModel { public string Name { get; set; } public decimal Price { get; set; } ... public double Latidude { get; set; } public double Longitude { get; set; } ... } 

In the view for FooWithLocationViewModel there is a <div> . We will use the data-* attributes that are valid in HTML5:

View:

 @model FooViewModel ... @foreach(FooWithLocationViewModel foo in Model.Foos) { <div class="foo" data-latitude="@(foo.Latitude)" data-longitude="@(foo.Longitude)"> <span>@foo.Name</span> <span>@foo.Price</span> ... </div> } <div id="map-canvas"></div> 

Now it's time for JavaScript, I assume you are using jQuery:

Initializing the map, adding markers and saving them in the markers array:

 function initialize() { var foos = $(".foo"); var markers = new Array(); var mapOptions = { ... }}; var mapCanvas = document.getElementById('map-canvas'); if (mapCanvas != null) { map = new google.maps.Map(mapCanvas, mapOptions); $.each(foos, function (key, value) { markers[key] = new google.maps.Marker({ map: map, draggable: false, animation: google.maps.Animation.DROP, position: new google.maps.LatLng( Number($(value).attr("data-latitude")), Number($(value).attr("data-longitude") )); }); google.maps.event.addListener(markers[key], 'click', function () { // If you need this... }); }); } } 

What's good about this approach is that everything is done in the function that initializes your Google map. Thus, your script should not be embedded in your view. We use a friendly HTML5 approach. And it's that simple.

+10
source

Use the web API and handle everything asynchronously. Pass the JSON object back to the client, analyze your information, remove the old tokens, and add new ones.

EDIT after your comment:

If you post some of your attempts and cannot work, we can help you deal with the problems you are facing. If you are just starting out:

http://www.asp.net/web-api - Great Guides on Using the Web API http://angularjs.org/ - Go to Angular for a GET request ( http://docs.angularjs.org/api/ng . $ http) and binding your results to the user interface

+2
source

I would like to propose an approach for this requirement:

  • On the search button, click - be it (POST or AJAX POST request), send the request to the server.

  • Search for the server (search).

  • There are two responsibilities for the search () action - 1. Show the search result. 2. Show the corresponding markers on the map

  • The result of the search will be the data and view, whether it be 'div' / 'table / tr / td'. This view is generated on the server without using any client resources and client-side processing time. Thus, a "SearchView" can return both data and a view.

  • Another responsibility is to show markers that match each search result. It is entirely the responsibility of the customer. Therefore, let us separate it from the first responsibility. Using the JSON serialization library inserts a serialized "marker" json array into the "SearchView" instead of mixing it with the search result. The only time you want the marker information to be rigidly attached to each search result, you want to highlight the markers when you click on individual search results. A use case may initially display all search results and show all markers. Then, when the user clicks / freezes (given that this is not intended for mobile devices, since the freeze cannot work there), you can move the marker or add a shortcut or additional information to the selected search result.

  • You can also have the script in a separate file so that you don’t have to load it with every search action. And from SearchView, you can simply call the JS InitializeMap () function, passing it serialized JSON markers and the starting position of the map.

  • Using JSON would be a better approach, and it would provide future flexibility for easily converting your application to AJAX. It’s also faster than parsing HTML using jQuery to get marker information.

     function InitializeMap(initialMapPosition,markers){ var latlng = new google.maps.LatLng(initialMapPosition.latitude,initialMapPosition.longitude); var options = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP // this could be as per your requirement. }; var map = new google.maps.Map($('#map-canvas')[0], options); // Place markers on map for( i = 0; i < markers.length; i++) { var latLng = new google.maps.LatLng(markers[i].lat, markers[i].lng); var marker = new google.maps.Marker({ position: latLng, map: map }); } 

    }

0
source

Here are my thoughts on this.

I recently made a project that was one AJAX-based web application (I know you are not looking for an AJAX-based solution, but stay with me).

I included Google maps in this application, which was used to display the location of different objects.

When the user was looking for something, instead of doing Geo-Coding in the browser (which was, from time to time, very slow), I sent a request to the server. On the server, the incoming text was Geo-encoded (using the Google API), and the result was cached in a local database for later use. If the same request is repeated again, I will bring Geo-cordinates from the database and send it to the client.

The return type was pretty simple. i.e.

 public class Marker { public double Lat{set;get;} public double Lon{set;get;} public string Title{set;get;} } 

On the client, I just iterate over the list and mark the markers on the map (markers are faster to build than a geocoding request).

Now the same thing can be done in post back. All you have to do is call the initialization function

 var markers = @Html.Action("GetMarkers") 

this will populate the var markers with a list of all your markers, which you can then iterate over.

Remember that the return type of GetMarkers is

  public JsonResult GetMarkers() { ... // returns List<Markers> } 
0
source

Source: https://habr.com/ru/post/949362/


All Articles