13

I'm sure this is a basic problem but I've hit my head against the wall too many times now, so hopefully someone will take pity on me!

I have the following example but all it does is show a grayed out box, no map at all. Can anyone tell me why?

I've checked that I'm actually returning a result and it seems to be working fine.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <style>
            html, body, #map-canvas {margin: 0;padding: 0;height: 100%;}
        </style>
    <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
    <script>
      var geocoder;
      var map;

      function initialize() 
      {
        geocoder = new google.maps.Geocoder();        
        geocoder.geocode( { 'address': "England"}, function(results, status) 
        {
          if (status == google.maps.GeocoderStatus.OK) 
          {
            var mapOptions = {
              zoom: 8,
              center: new google.maps.LatLng(results[0].geometry.location),
              mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            // Let's draw the map
            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

          } 
          else 
          {
            alert("Geocode was not successful for the following reason: " + status);
          }
        });
      }

    initialize();
    </script>
  </head>

  <body onload="">
 <div id="map-canvas" style="width: 320px; height: 480px;"></div>
</body>
</html>    
bencarter78
  • 3,555
  • 9
  • 35
  • 53

7 Answers7

9

Try resizing the browser window, give a shake to browser/drag it from browser tab with the cursor and you will see the map appearing.

From some strange reason in MVC partial view google map comes as blank, your map is working it just need to be resized.

Shaking a browser window with cursor sounds funny, but it works and I am not sure how to best describe it.

Thanks, Anurag

=======================================================================

my final working code is below:

`

<script type="text/javascript">

    $(document).ready(function () {
        (function () {
            var options = {
                zoom: 6,
                center: new google.maps.LatLng(-2.633333, 37.233334),
                mapTypeId: google.maps.MapTypeId.TERRAIN,
                mapTypeControl: false
            };

            // init map
            var map = new google.maps.Map(document.getElementById('map_canvas'), options);


            var arrLocation = [];
            $("#markerDiv").find("div").each(function () {
                var Lat = $(this).find("input[id='Latitude']").val();
                var Lon = $(this).find("input[id='Longitude']").val();
                var Id = $(this).find("input[id='Id']").val();
                var AssessmentDet = $(this).find("input[id='AssessmentDateTime']").val();
                var LocAcc = $(this).find("input[id='LocationAccuracy']").val();
                var assessorName = $(this).find("input[id='AssessorName']").val();
                var partnerName = $(this).find("input[id='PartnerName']").val();
                arrLocation.push({
                    Id: Id,
                    Latitude: Lat,
                    Longitude: Lon,
                    AssessmentDate: AssessmentDet,
                    LocationAccuracy: LocAcc,
                    AssessorDetail: assessorName,
                    PartnerName: partnerName
                    });
            });

            var allMarkers = [];

            for (var i = 0; i < arrLocation.length; i++) {

                //final position for marker, could be updated if another marker already exists in same position
                var latlng = new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude);
                var finalLatLng = latlng;
                var comparelatlng = "(" + arrLocation[i].Latitude + "," + arrLocation[i].Longitude + ")";
                var copyMarker = arrLocation[i];

                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(arrLocation[i].Latitude, arrLocation[i].Longitude),
                    map: map,
                    title: 'Equine # ' + arrLocation[i].Id,
                    icon:"abc.png"
                });


                var markerInfo = "Reference # : <b>" + arrLocation[i].Id + "</b><br/>";
                markerInfo = markerInfo + "Assessor : <b>" + arrLocation[i].AssessorDetail + "</b><br/>";
                markerInfo = markerInfo + "Date :  <b>" + arrLocation[i].AssessmentDate + "</b><br/>";
                markerInfo = markerInfo + "Partner :  <b>" + arrLocation[i].PartnerName + "</b>";(function (marker, i) {

  bindInfoWindow(marker, map, new google.maps.InfoWindow(), markerInfo);
                })(marker, i);
            }
        })();
    });

    function bindInfoWindow(marker, map, infowindow, html) {
        google.maps.event.addListener(marker, 'click', function () {
            infowindow.setContent(html);
            infowindow.open(map, marker);
        });
    }


</script>

`

Anurag
  • 368
  • 4
  • 9
  • 5
    I'm seeing the same thing and yes, resizing the browser window does kick it into finishing loading. No clue why or what to do about it. – David K. Hess Jan 20 '16 at 00:22
  • 1
    LOL, It works but what is the main reason behind this @Anurag – Bibek Sharma Feb 19 '16 at 10:11
  • I'm currently fighting against this behaviour and have tried various things like triggering a resize. My issue I think is due to how the DOM object is not loaded correctly in angular ui router –  Mar 04 '17 at 18:43
  • I am facing the same issue as well! Is there any way to fix it? – Anand May 15 '17 at 14:45
  • @Anand I got it working by creating a
    and then through ajax replaced the div content with _partial view text, also make sure in your partial view you have specified center point and zoom level for map as below, `code` var options = { zoom: 6, center: new google.maps.LatLng(-2.633333, 37.233334), mapTypeId: google.maps.MapTypeId.TERRAIN, mapTypeControl: false }; // init map var map = new google.maps.Map(document.getElementById('map_canvas'), options); `code`
    – Anurag May 17 '17 at 10:17
  • @Anurag, resizing the WHOLE window works, but I can't see what your code has to do with resizing. For me, jQuery trigger did not work. This worked: `window.dispatchEvent(new Event('resize'));`. Although the [best method](https://stackoverflow.com/a/43846782/673991) probably includes alternatives for IE, etc. – Bob Stein Feb 02 '18 at 22:14
8

results[0].geometry.location is already a latLng object so you can just say:

center: results[0].geometry.location

Find the working fiddle here : http://jsfiddle.net/87z9K/

The Dark Knight
  • 5,455
  • 11
  • 54
  • 95
putvande
  • 15,068
  • 3
  • 34
  • 50
3

It is because of the worng "google.maps.LatLng" provided. provide for a test the coords and it will work. replace the line

center: new google.maps.LatLng(results[0].geometry.location),

with

center: new google.maps.LatLng(-34.397, 150.644)

get England coords

Amigo
  • 47
  • 6
1

It wasn't exactly your issue, but closely related.

I found that I had to set the mapOptions with a valid centre, like so:

new google.maps.Map(mapCanvas, {
    center: new google.maps.LatLng(-34.397, 150.644)
});

If I didn't enter map options, or if I did and it didn't have a valid center set, I'd get a blank map that didn't load tiles.

andrewb
  • 5,200
  • 6
  • 36
  • 54
1

This can also occur if the height/width of the map is 0.

Debs
  • 29
  • 3
0

I tried to set map's MapTypeId and it helped as Anurag proposed:

map.setMapTypeId(google.maps.MapTypeId.TERRAIN);
Lopeta
  • 1
-4

I can see a general javascript issue with your code.

Your script might trying to embed the map in the page before the HTML is loaded.

Call the function like this (there are other ways).

<body onload="initialize()">
Padrig
  • 193
  • 1
  • 6