title: Google Maps API v3 / MVC 4 - geocoding an address that's passed to a (partial view) modal window in an MVC 4 application
body: <p>I have a list of search results. Beside each result is a button that when clicked launches a partial view housing a Bootstrap modal. </p>
  
  <p>The modal is strongly typed, the object passed in represents a residential property which has an address. The address is displayed in the modal header.</p>
  
  <p>I'm trying to get the address and pass it to a JS function that will geocode it and display it on a tab in the modal.</p>
  
  <p>What I've tried:</p>
  
  <pre><code>&lt;div class="modal-header"&gt;
      &lt;button type="button" class="close" data-dismiss="modal" aria-hidden="true"&gt;×&lt;/button&gt;
      &lt;h4 id="myModalLabel" data-id="@Model.Address.Line1,@if (Model.Address.Line2 != null)
      { @Model.Address.Line2; },@Model.Address.TownCity,@Model.Address.County"&gt;
          // display the address
      &lt;/h4&gt;
  &lt;/div&gt;
  
  &lt;div class="modal-body"&gt;
      &lt;div id="map-canvas" style="width: 400px; height: 400px"&gt;map canvas&lt;/div&gt;
  &lt;/div&gt;
  &lt;div class="modal-footer"&gt;
      &lt;button class="btn" data-dismiss="modal" aria-hidden="true"&gt;Close&lt;/button&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>JS as end of partial:</p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  initialize();
  
  var geocoder;
  var map;
  
  function initialize() {
      geocoder = new google.maps.Geocoder();
      var latlng = new google.maps.LatLng(-34.397, 150.644);
      var myOptions = {
          zoom: 8,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
  }
  
  function codeAddress() {
      var address = $('#myModalLabel').attr('data-id');
      geocoder.geocode({ 'address': address }, function (results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              map.setCenter(results[0].geometry.location);
              var marker = new google.maps.Marker({
                  map: map,
                  position: results[0].geometry.location
              });
          } else {
              alert("Geocode was not successful for the following reason: " + status);
          }
      });
  }
  google.maps.event.addDomListener(window, "load", initialize);
  </code></pre>
  
  <p></p>
  
  <p>So I've tried to add <code>data-id</code> attribute to the the modal label that displays the address and then select that in the <code>codeAddress()</code> function.</p>
  
  <p>The default map with the hard coded latlng displays, but the no geocoding is happening. Can someone point me in the right direction? Perhaps giving a more elegant way of getting the address from the model and passing it to <code>codeAddress()</code>. </p>