Get Latitude and Longitude on click event from Google map - javascript

I have implemented the Google map successfully. But one more thing has left to do. I need to retrieve the Longitude and Latitude data when the user clicks on the map (any co-ordinates). My entire code looks like this:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(<?=$decimalValueLon?>,<?=$decimalValueLat?>);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
// marker STARTS
var marker = new google.maps.Marker({
position: myLatlng,
title:"Click to view info!"
});
marker.setMap(map);
// marker ENDS
// info-window STARTS
var infowindow = new google.maps.InfoWindow({ content: "<div class='map_bg_logo'><span style='color:#1270a2;'><b><?=$row->bridge_name?></b> (<?=$row->bridge_no?>)</span><div style='border-top:1px dotted #ccc; height:1px; margin:5px 0;'></div><span style='color:#555;font-size:11px;'><b>Length: </b><?=$row->bridge_length?> meters</span></div>" });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
// info-window ENDS
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>`
Thanks in advance !

You can add a click-handler like you have a load handler:
google.maps.event.addListener(map, "click", function (e) {
//lat and lng is available in e object
var latLng = e.latLng;
});

<script>
var map;
function init_map() {
var opts = { 'center': new google.maps.LatLng(35.567980458012094,51.4599609375), 'zoom': 5, 'mapTypeId': google.maps.MapTypeId.ROADMAP }
map = new google.maps.Map(document.getElementById('mapdiv'), opts);
google.maps.event.addListener(map,'click',function(event) {
document.getElementById('latlongclicked').value = event.latLng.lat()
document.getElementById('lotlongclicked').value = event.latLng.lng()
});
google.maps.event.addListener(map,'mousemove',function(event) {
document.getElementById('latspan').innerHTML = event.latLng.lat()
document.getElementById('lngspan').innerHTML = event.latLng.lng()
});
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>

Related

how delete old markers on google map [duplicate]

This question already has answers here:
GoogleMaps v3 API Create only 1 marker on click
(5 answers)
Closed 5 years ago.
How to delete old markers and left only latest marker on google map.
I need only one marker no array.
Here is the code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div id="map" style="width: 100%; height: 400px;"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAA3ATL-GNAlXBPYYBMjdjoNWKUWnJ9i-c"></script>
<script>
var map;
function initialize() {
var haightAshbury = new google.maps.LatLng(52.62440324134009, 4.88054275512695);
var mapOptions = {
zoom: 8,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
// Add a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();
jQuery("#lat").val(lat);
jQuery("#lng").val(lng);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="panel">
<input type="hidden" value="" name="lat" id="lat">
<br/>
<input type="hidden" value="" name="lng" id="lng">
If I understood you right you can make a click maker that appears on the map if you click it and changes the position if you click somewhere else:
var clickmarker = new google.maps.Marker({
draggable: false
});
google.maps.event.addListener(map, 'click', function(event) {
clickmarker.setPosition(event.latLng);
clickmarker.setMap(map);
clickmarker.setAnimation(google.maps.Animation.DROP);
var lat = clickmarker.getPosition().lat();
var lng = clickmarker.getPosition().lng();
jQuery("#lat").val(lat);
jQuery("#lng").val(lng)
});
So your code would be:
<script>
var map;
function initialize() {
var haightAshbury = new google.maps.LatLng(52.62440324134009, 4.88054275512695);
var mapOptions = {
zoom: 8,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
var clickmarker = new google.maps.Marker({
draggable: false
});
google.maps.event.addListener(map, 'click', function(event) {
clickmarker.setPosition(event.latLng);
clickmarker.setMap(map);
clickmarker.setAnimation(google.maps.Animation.DROP);
var lat = clickmarker.getPosition().lat();
var lng = clickmarker.getPosition().lng();
jQuery("#lat").val(lat);
jQuery("#lng").val(lng)
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Here's the doc: https://developers.google.com/maps/documentation/javascript/examples/marker-remove
Seems you just need to remove all the markers before adding the new one and you're good.
You can just change coordinates of existing marker
var marker;
if (marker) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map
});
}

Is there a way to add location to the label of a marker that is randomly placed in google maps with javascript?

Is it possible to add the LatLng to the label of the marker that is placed at random to show where that marker is? Also considering the infoWindow option but have not been successful yet.
var map;
var markers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markersIndex = 0;
function initialize() {
var Wilm = new google.maps.LatLng(34.2257,-77.9447);
var mapOptions = {
zoom: 12,
center: Wilm,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById('map-
canvas'),mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
label: markers[markersIndex++ % markers.length],
map: map
});
google.maps.event.addListener(marker, 'rightclick', function(event) {
marker.setMap(null);
});
markers.push(marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
Not sure what you mean by a label.
this will add markers to the map with an info window with the latlng:
function initMap() {
var Wilm = new google.maps.LatLng(34.2257, -77.9447);
var mapOptions = {
zoom: 12,
center: Wilm,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
var contentString = 'Lat' + marker.getPosition().lat() + ', lng: ' + marker.getPosition().lng();
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
function initMap() {
var Wilm = new google.maps.LatLng(34.2257, -77.9447);
var mapOptions = {
zoom: 12,
center: Wilm,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
var contentString = 'Lat' + marker.getPosition().lat() + ', lng: ' + marker.getPosition().lng();
var infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=KEY&callback=initMap">
</script>

Google marker is not being displayed on map

I have written code to display a marker on a googlemap. The code is copied almost verbatim, from the Google API docs. Yet the marker is not displaying on the page.
Here is my code: What am I doing wrong?
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() {
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
var marker = new google.maps.Marker({
position: central_location,
map: map,
title: 'This is the title'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
marker.setMap(map);
});
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
I notice that there are similar questions, the only thing that seems to be different with my question is that I am creating my marker in the jQuery ready() event - NOT the initialize() function.
Is this why the marker is not been displayed?
Note: I don't remember reading anything in the Google API docs that states that markers should be created when the map is being created, so that can't obviously be the case
Move your marker creation to the initialize function.
$(document).ready(function(){}) works when DOM elements are loaded, which doesn't necessarily mean that the map is loaded. So if you try to create the marker in the document ready function, the map might not be created then, once the map is ready map variable has the map object, so you can make the marker on that, and you can add the markers dynamically after the map is loaded.
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
console.log('map loaded');
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
makePin(42.745334, 12.738430);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function(){
console.log('document loaded');
})
function makePin(lat, long){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, long),
map: map,
title: 'This is the title'
});
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<button onclick="makePin(42.749334, 12.739430)">Add Pin</button>
<div id="map"></div>
How can you make marker without loaded map. Map need to initialize first then marker will work
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: central_location,
map: map,
title: 'This is the title'
});
marker.addListener('click', function () {
infowindow.open(map, marker);
});
marker.setMap(map);
}
Here is the solution:
var map;
var central_location = new google.maps.LatLng(42.745334, 12.738430);
function initialize() {
var mapCanvas = document.getElementById('map');
var mapOptions = {
center: central_location,
zoom: 14,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: central_location,
map: map,
title: 'This is the title'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() {
var infowindow = new google.maps.InfoWindow({
content: '<div>Hello</div>'
});
});
#map {
width: 500px;
height: 380px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript" style=""></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

Geolocation Change Marker Position

I use geolocation and I can view map my coordinates. Then, marker put the coordinate.
I want to change marker position.
My code here:
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition,showError);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
lat=position.coords.latitude;
lon=position.coords.longitude;
latlon=new google.maps.LatLng(lat, lon)
mapholder=document.getElementById('mapholder')
mapholder.style.height='250px';
mapholder.style.width='100%';
var myOptions={
center:latlon,zoom:14,
mapTypeId:google.maps.MapTypeId.ROADMAP,
mapTypeControl:false,
navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL}
};
var map=new google.maps.Map(document.getElementById("mapholder"),myOptions);
var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"});
This code get my location coordinates. How can i change marker position?
I am sorry Eren about the my previous answer.I misunderstood.I think , this is correct one what you needed.
Display latitude and longitude on marker movement
Refer this site
I found a solution in this page. My problem is solved with this.
refer this
and this site
var map;
var myCenter = new google.maps.LatLng(37, 35);
var markersArray = [];
function clearOverlays() {
for (var i = 0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
function initialize() {
var mapProp = {
center: myCenter,
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
google.maps.event.addListener(map, 'click', function (event) {
placeMarker(event.latLng);
});
}
function placeMarker(location) {
clearOverlays();
var marker = new google.maps.Marker({
position: location,
map: map,
});
markersArray.push(marker);
var infowindow = new google.maps.InfoWindow({
content: 'Latitude: ' + location.lat() + '<br>Longitude: ' + location.lng()
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
moveBus() is getting called before initialize(). Try putting that line at the end of your initialize() function. Also Lat/Lon 0,0 is off the map (it's coordinates, not pixels), so you can't see it when it moves. Try 54,54. If you want the center of the map to move to the new location, use panTo().
Demo: http: //jsfiddle.net/ThinkingStiff/Rsp22/
HTML:
<script src = "http://maps.googleapis.com/maps/api/js?sensor=false" > </script> <div id = "map-canvas"> </div>
CSS:
#map-canvas {
height: 400 px;
width: 500 px;
}
Script:
function initialize() {
var myLatLng = new google.maps.LatLng(50, 50),
myOptions = {
zoom: 4,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
marker = new google.maps.Marker({
position: myLatLng,
map: map
});
marker.setMap(map);
moveBus(map, marker);
}
function moveBus(map, marker) {
marker.setPosition(new google.maps.LatLng(0, 0));
map.panTo(new google.maps.LatLng(0, 0));
};
initialize();

Load Google Maps map on click event

if I'm having code below to initialize google map onload
<script src="https://maps.googleapis.com/maps/api/js"></script>
<script>
function initialize() {
var lat = 45.430817;
var lon = 12.331516;
var mapCanvas = document.getElementById('map-canvas');
var mapOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(mapCanvas, mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
</script>
how can I modify this to load this map only on certain event (click on tab with id = tab-link)
<li id="tab-link">Show map </li>
var myCenter=new google.maps.LatLng(45.430817, 12.331516);
var marker=new google.maps.Marker({
position:myCenter
});
function initialize() {
var mapProp = {
center:myCenter,
zoom: 14,
draggable: false,
scrollwheel: false
};
var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
};
$(document).ready(function(){
$('#tab-link').bind('click', function() {
initialize()
});
});

Categories

Resources