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>
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)
);
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);
Related
I have created a simple button that asks for latitude and longitude and if the users inputs lets say 22,15 a marker should show up but for some reason my code isn't working
the code is:
var map;
var marker;
var myLatLng = new google.maps.LatLng();
function initialize() {
var myLatLng = new google.maps.LatLng(45.4375, 12.3358);
myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
function zoomto() {
map.set('zoom', parseInt(prompt('zoom value')));
}
function setCentre()
{
map.setOptions({center: new google.maps.LatLng(prompt("Latitude: "),prompt("Longitude: "))});
}
google.maps.event.addDomListener(window, 'load', initialize);
function Marker1 () {
map.setOptions({Marker: new google.maps.LatLng(prompt("Latitude: "),prompt("Longitude: "))});
}
function Marker () {
map.setOptions({Marker: new google.maps.LatLng(prompt("Latitude: "),prompt("Longitude: "),prompt("Color "),prompt("style "),prompt("number "))});
}
var marker = new google.maps.Marker({
position: myLatLng,
title: 'Hello World'
});
I have many buttons zoom or move to which both work however I can't get the markers to work.
thanks for looking and help.
Here is an example on how to center a map from user input (lat/lng) that includes validation.
It checks whether the lat and lng are valid. More information can be found here regarding the latitude min/max range.
HTML
<form id="mapCenterForm">
Lat:
<input type="text" id="lat" />
<br />Lng:
<input type="text" id="lng" />
<br />
<input type="submit" value="Center map" />
</form>
JavaScript
// Calculate maximum latitude value on mercator projection
var maxLat = Math.atan(Math.sinh(Math.PI)) * 180 / Math.PI;
function initialize() {
var center = new google.maps.LatLng(0, 0);
var mapOptions = {
zoom: 3,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
// DOM event listener for the center map form submit
google.maps.event.addDomListener(document.getElementById('mapCenterForm'), 'submit', function (e) {
e.preventDefault();
// Get lat and lng values from input fields
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
// Validate user input as numbers
lat = (!isNumber(lat) ? 0 : lat);
lng = (!isNumber(lng) ? 0 : lng);
// Validate user input as valid lat/lng values
lat = latRange(lat);
lng = lngRange(lng);
// Replace input values
document.getElementById('lat').value = lat;
document.getElementById('lng').value = lng;
// Create LatLng object
var mapCenter = new google.maps.LatLng(lat, lng);
new google.maps.Marker({
position: mapCenter,
title: 'Marker title',
map: map
});
// Center map
map.setCenter(mapCenter);
});
}
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function latRange(n) {
return Math.min(Math.max(parseInt(n), -maxLat), maxLat);
}
function lngRange(n) {
return Math.min(Math.max(parseInt(n), -180), 180);
}
initialize();
JSFiddle demo
I was roaming on this site for any info on geocoding a marker. However, I have tried some of the answers but I did not manage to make it work (I am an amateur when it comes to coding), so could someone please help me with the geocoding of my marker? Apparantly, the marker is missing when using this code. I need to geocode postcode in this case, which is the zip code 1058JA. Thanks in advance!
var geocoder;
var map;
var Postcode;
Postcode = '1058JA';
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.368465, 4.903921);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
function codeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode( {'address': document.getElementById("address").value },
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
Postcode = results[0].geometry.location;
map = new google.maps.Map(document.getElementById("map_canvas"),
{
center: Postcode,
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker=new google.maps.Marker({
position:results[0].geometry.location,
});
marker.setMap(map);
}
else {
document.getElementById("address").value = status;
}
}
);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
There are a few things wrong with your code.
1) codeAddress is never called (as Anto Jurković notes).
2) A new instance of map is created within codeAddress if it were ever called which is redundant.
3) While you've specified Postcode as a string at the top of the code, the geocoder is looking for the value of a input element instead.
Your code should something like this:
var geocoder;
var map;
var Postcode;
Postcode = '1058JA';
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(52.368465, 4.903921);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': Postcode }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
position: results[0].geometry.location,
});
marker.setMap(map);
} else {
document.getElementById("address").value = status;
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Demo
I have used the following code to display the marker on the location I have dynamically searched for(code). Now I want to highlight the searched location boundary. (For instance, if I search 'Tokyo', it should mark the boundary of 'Tokyo'(chk the image for reference).
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else
{
$('#noResults').html("Unsuccessful:" + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
i am trying to get address using reverse geocoding.
but there is some problem in geocoder.geocode({...}) line. even normal alert message also not display.
function initialize() {
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(23.0171240, 72.5330533),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
var input=e.latLng;
var lat = parseFloat(input.lat());
var lng = parseFloat(input.lng());
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert(results[1].formatted_address);
}
});
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
google.maps.event.addDomListener(window, 'load', initialize);
add below line inside initialize() function.
var geocoder = new google.maps.Geocoder();
Hey I'm new to the google maps api, and I have an embedded map, i'm using geolocation to get the users lat and long, and i'm then filling in the gaps in the maps api. The map, however doesn't work when I use the generated lat and long, but does work if i just type one in
Non-working code:
var map;
var infowindow;
function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position)
{
var latlon = new google.maps.LatLng( position.coords.latitude + "," + position.coords.longitude );
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Working code
var map;
var infowindow;
function initialize() {
var latlon = new google.maps.LatLng(-33.8665433, 151.1956316);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: latlon,
zoom: 15,
disableDefaultUI: true
});
var request = {
location: latlon,
radius: 555,
types: ['bar']
};
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
alert(place.name);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Any help if appreciated :)
Replace your line:
var latlon = new google.maps.LatLng
(position.coords.latitude + "," + position.coords.longitude);
with
var latlon = new google.maps.LatLng
(position.coords.latitude, position.coords.longitude);
The problem is in concatenating two values into one where constructor expects two parameters.