0

I'm trying to add a marker using a button in Google Maps and I'm getting the error, cannot read property lat of null. I'm not that good in Javascript, any help?

 function setmarker(){
        setLatLng = new google.maps.LatLng(document.getElementById('latitude').value,document.getElementById('longitude').value); 
        alert(setLatLng);
        var map = new google.maps.Map(document.getElementById('map-canvas'),
          mapOptions);

        var mapOptions = {
        zoom: 8,
        //center: new google.maps.LatLng(-1.2921897,36.8288574)
      };


        var marker = new google.maps.Marker({
          position: setLatLng,
          map: map,
          title: 'Obtained coordinate'
        });

    }
    </script>
  </head>
  <body>
<div id="map-canvas"></div>


<div class="side-panel">
  <div>Latitude:<br><input type="text" name="latitude" id="latitude" ></div>
  <div>Longitude:<br><input type="text" name="longitude" id="longitude"></div><br>
  <!-- <input type="submit" onsubmit="setmarker();"> -->
  <button onclick="setmarker()">Show Marker</button>
</div>
3
  • can you create an example on jsfiddle.net, it will make it easier seeing full code. Commented Oct 24, 2014 at 16:09
  • Presumably you're only pressing the 'Show Marker' button after entering values in the latitude and longitude form fields? Commented Oct 24, 2014 at 16:18
  • Yes @duncan, I want to press the button after entering values in the longitude and latitude form fields. Commented Oct 27, 2014 at 15:16

2 Answers 2

1

When you do document.getElementById('latitude').value that returns the value as a string e.g. "51.23546" instead of the floating point number that Google's API expects.

To make sure they get passed to Google as floats, try:

setLatLng = new google.maps.LatLng(
    parseFloat(document.getElementById('latitude').value),       
    parseFloat(document.getElementById('longitude').value)
); 
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, the method above still doesn't work. I still get the error "Cannot read property 'lat' of null".
what does console.log(document.getElementById('latitude')) give you?
When I do this, i get undefined. By the way on clicking the button, the map goes to a blank gray screen. I don't understand why it doesn't read the latitude float...
if it's undefined that implies that you don't have an element in the DOM with id 'latitude'. Your own answer suggests that it's called 'latlng' instead.
0

Thanks for all the answers, stumbled upon the answer in the name of Reverse GeoCoding Service from Google that exactly did what I wanted to quite easily and in the exact way. From the API: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse

var geocoder;
var map;
var infowindow = new google.maps.InfoWindow();
var marker;
function initialize() {
  geocoder = new google.maps.Geocoder();
  var latlng = new google.maps.LatLng(40.730885,-73.997383);
  var mapOptions = {
    zoom: 8,
    center: latlng,
    mapTypeId: 'roadmap'
  }
  map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}

function codeLatLng() {
  var input = document.getElementById('latlng').value;
  var latlngStr = input.split(',', 2);
  var lat = parseFloat(latlngStr[0]);
  var lng = parseFloat(latlngStr[1]);
  var latlng = new google.maps.LatLng(lat, lng);
  geocoder.geocode({'latLng': latlng}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      if (results[1]) {
        map.setZoom(11);
        marker = new google.maps.Marker({
            position: latlng,
            map: map
        });
        infowindow.setContent(results[1].formatted_address);
        infowindow.open(map, marker);
      } else {
        alert('No results found');
      }
    } else {
      alert('Geocoder failed due to: ' + status);
    }
  });
}

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

3 Comments

This is completely different from your original code, where you had two input fields for each of latitude and longitude. Now I'm assuming you have one field called 'latlng' and you're using parseFloat() to convert the values in there from strings to floats exactly as I'd suggested you do previously.
... and if you've got latitude and longitude values, you shouldn't need to reverse-geocode them if all you're doing is creating a marker. If that's so you can convert the latlng to an address for the benefit of adding content to your infowindow, that's a completely different issue not mentioned in your question.
Sorry, about that, I meant if I took the latitude and longitude from a text field, in the same way I was doing in the question, the above method would work the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.