MVC 4 and Google Maps API v3

前端 未结 4 761
再見小時候
再見小時候 2021-02-06 08:52

I\'m incorporating Google Maps into my MVC 4 application. Fairly straightforward to do. However, I have a question concerning the best way to add multiple markers dynamically. M

4条回答
  •  我寻月下人不归
    2021-02-06 09:29

    Would like to suggest an approach for this requirement:

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

    2. Perform the search on server 'search()' action.

    3. There are two responsibilities of search() action - 1. Show search result. 2. Show corresponding Markers on Map

    4. Search result will be the data and representation, be it 'div'/'table/tr/td'. This representation is generated on server without using any client resources and client side processing time. So the 'SearchView' can return both data and representation.

    5. Another responsibility is showing the markers corresponding to each search result. This is totally client responsibility. So lets keep it separate from the first responsibility. Using the JSON serialization library inject the serialized 'markers' json array in the 'SearchView' instead of mixing it with search result. The only time you might want to have the markers details with tightly bind to each search result is when you want to highlight the markers on click of individual search results. The use case could be initially show all the search results and show all the markers. Then when user clicks/hovers over (considering this is not targeted for mobile as hover cannot work there) the individual search result you can reposition the marker or add label or more information to selected search result.

    6. Also you might want to have the script in a separate file to avoid loading it on each search action. And from SearchView you can just call the 'InitializeMap()' JS function passing it the JSON serialized Markers and the initial map position.

    7. Using the JSON would be better approach and it provides the future flexibility to convert the application to AJAX easily. Also it is faster than parsing the HTML using Jquery for getting the marker details.

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

      }

提交回复
热议问题