bnjmn.myers
bnjmn.myers

Reputation: 439

Dynamically add marker to Google Map

I have a Google Map that is loading up to the correct lat and lon. I would like to place a marker at that lat and lon.

Here is my code

    function initialize() {
        var mapCanvas = document.getElementById('map_canvas2');
        var myLatLng = { lat: contactLatitude, lng: contactLongitude };
        var mapOptions = {
            center: new google.maps.LatLng(contactLatitude, contactLongitude),
            zoom: 8,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        }
        var map = new google.maps.Map(mapCanvas, mapOptions);
        addMarker(myLatLng, map);
    }

    function addMarker(location, map) {
        var marker = new google.maps.Marker({
            position: location,
            title: 'Home Center'
        });
    }

    google.maps.event.addDomListener(window, 'load', initialize);

Everything displays just fine but the marker doesn't show up. What am I doing wrong?

Upvotes: 4

Views: 20639

Answers (1)

geocodezip
geocodezip

Reputation: 161404

You aren't adding the marker to the map. Either:

function addMarker(location, map) {
  var marker = new google.maps.Marker({
      position: location,
      title: 'Home Center',
      map:map
  });
}

or

function addMarker(location, map) {
  var marker = new google.maps.Marker({
      position: location,
      title: 'Home Center',
  });
  marker.setMap(map);
}

proof of concept fiddle

code snippet:

var contactLatitude = 42;
var contactLongitude = -72;

function initialize() {
  var mapCanvas = document.getElementById('map_canvas2');
  var myLatLng = {
    lat: contactLatitude,
    lng: contactLongitude
  };
  var mapOptions = {
    center: new google.maps.LatLng(contactLatitude, contactLongitude),
    zoom: 8,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }
  var map = new google.maps.Map(mapCanvas, mapOptions);
  addMarker(myLatLng, map);
}

function addMarker(location, map) {
  var marker = new google.maps.Marker({
    position: location,
    title: 'Home Center',
    map: map
  });
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas2 {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map_canvas2" style="border: 2px solid #3872ac;"></div>

Upvotes: 10

Related Questions