0

I have a button which if clicked displays the users location on a map. Currently tough I get this error Uncaught TypeError: Cannot set property 'position' of undefined

This is my code:

 <div class="col-sm-offset-4 col-sm-4"> <input type="button" value="Show my location on Map" id="mapButton"> <article></article> </div> $('#mapButton').click(function() { $( "#mapcontainer" ).remove(); function success(position){ var mapcanvas = document.createElement('div'); mapcanvas.id = 'mapcontainer'; mapcanvas.style.height = '300px'; mapcanvas.style.width = '300px'; document.querySelector('article').appendChild(mapcanvas); var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); alert(coords); var options = { zoom: 15, center: coords, mapTypeControl: false, navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL }, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map("mapcontainer",options)[0]; marker = new google.maps.Marker({ position: coords, map: map, title:"You are here!" }); } if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(success); } else { error('Geo Location is not supported'); } 

});

Why does it throw this error?

JSFiddle

1
  • Can you create a jsfiddle example? Commented Aug 28, 2014 at 10:49

1 Answer 1

1

First parameter to map, is a div element. instead of passing 'mapcontainer', pass

document.getElementById("mapcontainer")

Working example

 var map = new google.maps.Map(document.getElementById("mapcontainer"),options)[0]; var marker = new google.maps.Marker({ 'position': coords, map: map, title:"You are here!" }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.