user3195417
user3195417

Reputation: 329

Showing Marker with Google Maps API

I'm trying to set up a simple page to display a marker on a location, using Google Maps API. However I'm not getting the marker with this code, which is based on Googles example code here. I changed the source from

"https://maps.googleapis.com/maps/api/js?key=API_KEY&sensor=false"

to

"http://maps.google.com/maps/api/js?sensor=false"

because it was recommended here for the purpose of avoiding to use a API key. The var marker declaration is copied from google here. What must change for my marker to appear?


<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
    </script>
    <script type="text/javascript">
      function initialize() {

        var location = new google.maps.LatLng(59.272, 10.418);  

        var mapOptions = {
          center: location,
          zoom: 8
        };

        var marker = new google.maps.Marker({
            position: location,
            map: map,
            title: 'Hello World!'
        });

        var map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"/>
  </body>
</html>

Upvotes: 1

Views: 2392

Answers (2)

Andy
Andy

Reputation: 63514

Move the line setting up the map before the line setting up the marker, as the marker uses the map in its invocation:

function initialize() {
  var location = new google.maps.LatLng(59.272, 10.418);

  var mapOptions = {
    center: location,
    zoom: 8
  };

  var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

  var marker = new google.maps.Marker({
    position: location,
    map: map,
    title: 'Hello World!'
  });
}

Upvotes: 5

ChrisSwires
ChrisSwires

Reputation: 2723

Move the declaration of your marker to after the map declaration and then assign the marker to the map like so:

var map = new google.maps.Map(document.getElementById("map-canvas"),
        mapOptions);

var marker = new google.maps.Marker({
        position: location,
        map: map,
        title: 'Hello World!'
    });

marker.setMap(map);

Note, setting the map is optional, and can be used instead of setting the map at instantiation of the marker.

Upvotes: 0

Related Questions