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>
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);
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다