简体   繁体   中英

Can't add Marker on Google maps Api

I have tried numerous variations but none display the Marker on the map. Could anyone help, please?

</script>
  <script>
  function initialize() {
      var latlng = new google.maps.LatLng(51.51697, -0.14650);
      var myOptions = {
          zoom: 16,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
      };
      var map = new google.maps.Map(document.getElementById("map_canvas"),
      myOptions);
  }

  // To add the marker to the map, use the 'map' property
    var marker = new google.maps.Marker({
    position: new google.maps.LatLng(51.51697, -0.14650),
    map: map,
    title:"HERE"
});

// To add the marker to the map, call setMap();
marker.setMap(map);
  </script>

Thanks a million.

There are two reasons why the marker doesn't show up:

  1. The map variable is local inside the initialize function, so you can't reach it from code outside the function.

  2. The initialize function is called from the load event, so you try to add the marker to the map before it exists.

Add the marker to the map inside the initialize function. There you have access to the variable, and the map is already created when you add the marker.

If you need to access the map outside the initialize function, declare the variable map outside the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM