Get Lat/Long with click by Javascript [duplicate] - javascript

This question already has answers here:
Google Maps HTML5 click to get lat, long
(3 answers)
Closed 5 years ago.
I want when I click on map I can get Lat/Long and show it in alert()
This is my code:
<!DOCTYPE html>
<html>
<body>
<div id="googleMap" style="width:100%;height:400px;"></div>
<script>
function myMap() {
var mapProp= {
center:new google.maps.LatLng(51.508742,-0.120850),
zoom:5,
};
var map=new google.maps.Map(document.getElementById("googleMap"),mapProp);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
</body>
</html>
My code is simple and I got it from This link

Something like:
google.maps.event.addListener(map, 'click', function(event) {
// get a marker if you want
marker = new google.maps.Marker({position: event.latLng, map: map});
// alert out the lat/lng...
alert('Lat:' + event.latLng.lat() + ', Lng:' + event.latLng.lng());
});

Related

Can't get js function to load in html

I've just started trying to develop a website and I'd like to keep the html and javascript separate if I can. I'm trying to put a marker on a map, have the co-ordinates placed in a text box as part of a form, and have them sent to the database when the user submits the form. The code works when it's all inside the html doc, but when I try to separate it it doesnt work. Well, the map still shows up and I can set a marker on it, but it doesn't capture the co-ordinates.
In the head of the html
<script type="text/javascript" src="mapSubmitSighting.js"></script>
<body onload="initMap()">
Inside the div where I want the js to execute
<div id="map">
<div class="map" onclick="initMap();">
<script defer
src="https://maps.googleapis.com/maps/api/js?key==initMap"></script>
</div>
The js file
!function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 54.621277, lng: -6.692649 }
});
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
!function placeMarkerAndPanTo(latLng, map) {
var marker = new google.maps.Marker({
position: latLng,
map: map
});
map.panTo(latLng);
document.getElementById("lat").value = latLng.lat();
document.getElementById("lng").value = latLng.lng();
}
I know there's lots wrong with this but if I could just work out how to get the javascript to work it'd be a start. Thank you!
Most part of your code actually works.
Did a few modification though.
Added initial marker position as I noticed that you intended to do this on your sample code.
Also, refactored your code so needed routines will be re-usable.
Please check below.
HTML
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px;
width: 50%;
}
</style>
<script src="mapSubmitSighting.js"></script>
</head>
<body>
<div id="map"></div>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyD72DV80rL8PBw2BTTWOwHV3NPSQdx24D8&callback=initMap"></script>
<br/>
<div>
Latitude: <input type="text" id="lat"/><br/><br/>
Longitude: <input type="text" id="lng"/>
</div>
</body>
</html>
JS
function initMap() {
var initialLocation = {lat: 54.621277, lng: -6.692649 };
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: initialLocation
});
var marker = setMarker(initialLocation, map);
setTextCoordinates(initialLocation.lat, initialLocation.lng);
google.maps.event.trigger(map, "resize");
map.addListener('click', function(e) {
placeMarkerAndPanTo(e.latLng, map);
});
}
function placeMarkerAndPanTo(latLng, map) {
var marker = setMarker(latLng, map);
map.panTo(latLng);
setTextCoordinates(latLng.lat(), latLng.lng());
}
function setMarker(latLng, map){
var marker = new google.maps.Marker({
position: latLng,
map: map
});
return marker;
}
function setTextCoordinates(lat, lng){
document.getElementById("lat").value = lat;
document.getElementById("lng").value = lng;
}
Output
Hope this helps!
You are probably not linking the file correctly.
You can open the developer tools (F12 in Chrome, or just right-click on some part of the page and select Inspect Element) and look at the errors in the console.
Most likely there's a 404 error. Look at the URL of the file, does it match the place where it is supposed to be? Are you missing a folder? Did you forget to upload it? Let us know so we can further assist!
You also do not need the ! in the beginning of your js function. This is preventing your html from reading the js file.
should look like -->
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,`enter code here`

Google Map does not work in php [duplicate]

This question already has answers here:
ERROR: Google Maps API error: MissingKeyMapError
(7 answers)
Closed 6 years ago.
I want to show map of my university but it load for 1 sec and then tell
MissingKeyMapError
and
Sorry! Something went wrong.
This page didn't load Google Maps correctly. See the JavaScript console for technical details.
I use Google Maps JavaScript API and Web browser (javaScript).Hear is my code :
<script src='https://maps.googleapis.com/maps/api/js?key=AIzaSyDNi7fQreXQ_AvjDEbMBGtBo2XoP5QkxRs'></script>
<div style='overflow:hidden;height:440px;width:700px;'>
<div id='gmap_canvas' style='height:440px;width:700px;'></div>
<style>#gmap_canvas img {
max-width: none !important;
background: none !important
} </style>
</div>
<script type='text/javascript'>
function init_map() {
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(22.3475365, 91.81233240000006),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(22.3475365, 91.81233240000006)
});
infowindow = new google.maps.InfoWindow({content: '<strong>University of Chittagong</strong><br>Chittagong , Bangladesh<br>'});
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
infowindow.open(map, marker);
}
google.maps.event.addDomListener(window, 'load', init_map);
</script>
</head>
This is my full code . Please help me for my project.
Where did you get that key? Like Vishnu said, that should be the problem. If you did not get it from the Google Maps API documentation you should go there and get a new one (they are accessible for free). Also, the title of your question seems misleading in my opinion, as you do not seem to use PHP.

Google maps API v3 - Marker disappears after setPosition [duplicate]

This question already has an answer here:
google maps move marker with lat/lng from ajax success returned data
(1 answer)
Closed 8 years ago.
I'm having a problem with the maps markers. The map and marker load fine on the inital pageload. But when I try to update the marker location it simply disappears. The Alert window gives the correct coördinates. What am I doing wrong here?
Code:
<script>
var myCenter=new google.maps.LatLng(<?php echo $loc; ?>);
function initialize()
{
var mapProp = {
center:new google.maps.LatLng(<?php echo $loc; ?>),
zoom:15,
mapTypeId:google.maps.MapTypeId.ROADMAP,
};
var map=new google.maps.Map(document.getElementById("googleMap")
,mapProp);
var marker=new google.maps.Marker({
position:myCenter,
});
marker.setMap(map);
setInterval(function(){
jQuery.get('loc.php?v=<?php echo $_GET['voertuignummer'];?>', function(data) {
alert(data);
position = new google.maps.LatLng(data);
marker.setPosition(position);
map.setCenter(position);
});
}, 15000);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
function(data) {
alert(data);
position = new google.maps.LatLng(data);
..
Looks very wrong; data is a string, probably containing "lat, lng", which google.maps.LatLng cannot be initialized with. new google.maps.LatLng requires a pair of type number in the arguments, like (number, number).
Do this instead :
data = data.split(',');
position = new google.maps.LatLng(parseFloat(data[0]), parseFloat(data[1]));

How can I assign latlng coordinate values to JS variables

Hello I am learning Google Map API from w3schools. I am new to JS and want to assign location.lat() and location.lng() to JavaScript variables. This is the copied code of tutorials. I am trying to assign the values as;
var latid=location.lat(); but I think lat() is returning nothing.
I have to save coordinates in database. If it is the wrong approach then please tell me what can I do to save lnglat coordinates in my database.
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=mykeyishidden&sensor=false"></script>
<script>
var map;
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
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) {
var marker = new google.maps.Marker({
position: location,
map: map,
});
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);
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
</body>
</html>
I see you are trying to access location through location.lat() but do not see anything on location on your entire script. I was expecting to see something like
google.maps.GeocoderGeometry.location
instantiated somewhere.
For your purpose, I think it is better to try the following if it is what you meant:
google.maps.LatLng.lat() // Returns latitude
google.maps.LatLng.lng() // Returns longitude
I ran your page and looked into the Console.
In the placeMarker(location), location has these attributes.
A: -1.8017578125
k: 49.03786794532644
Your lat() and lng() are actually returning values, not zero! So, for example, if you needed to store these in use somewhere else in your program, your code would have these things added...
<script>
var map;
var myCenter=new google.maps.LatLng(51.508742,-0.120850);
var myLatLng;
var myLatLngs[];
...
function placeMarker(location) {
...
myLatLng = {lat:location.lat(),lng:location.lng()};
console.log("Lat: " + myLatLng.lat + " Lng: " + myLatLng.lng);
myLatLngs.push(myLatLng);
infowindow.open(map,marker);
}
...
Now you've got myLatLng which stores the latitude and longitude, myLatLngs which is an array of every time the user clicks and stores these coordinates in order, and a console.log to display it to you to confirm in the console.
If you don't know how to access the browser console by looking at this thread: https://webmasters.stackexchange.com/questions/8525/how-to-open-the-javascript-console-in-different-browsers

array losing scope when moved into a for ( in ) loop [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
This is really driving me crazy. Why does my array lose scope moving it into a for loop? Please have a look at this code, the var 'marker' is losing scope near the beginning of this script. ANY thoughts welcome.
<!DOCTYPE html>
<html>
<head>
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
//var cell={};
var cellcenter = new Array();
var lat = ''; var lng='';
$(document).ready(function(){
i=0;
$.getJSON('http://www.perivision.net/testing/containment/containment.php', function(data) {
var marker = new Array();
marker[0]=9;
$('#output').html('this works '+marker[0]);
for (index in data) {
i++;
$('#output').html(' this does not '+marker[0]);
for (element in data[index]) {
//console.log(element);
//console.log(data[index][element]);
if (element=="attribute8"){
lat=data[index][element];
}
if (element=="attribute9"){
//cell[i]=data[index][element];
lng=data[index][element];
cellcenter[i]=new google.maps.LatLng(lat,lng);
var myLatlng = new google.maps.LatLng(51.508742,-0.120850);
var mapOptions = {
zoom: 4,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map= new google.maps.Map(document.getElementById("googleMap"),mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:"Hello World!"
});
marker[i] = new google.maps.Marker({
position: cellcenter[i],
title:"Hello World!"+i
});
// To add the marker to the map, call setMap();
marker.setMap(map);
//marker[0].setMap(map);
marker[i].setMap(map);
//$('#output').html('re '+marker[0]);
//console.log('ping '+i+' '+cellcenter[i]);
}
}
}
});
});
function donothing(){
}
</script>
</head>
<body>
<div id="googleMap" style="width:500px;height:380px;"></div>
<button id="requestDataBtn">Get Data</button><br />
<div id='output'></div>
</body>
</html>
var marker = new google.maps.Marker
This is your problem. You are giving the same name marker to some other object. Now, Javascript interpreter scans the entire JS code and looks for any var definitions before executing. Thats why eventhough you have defined marker mch below it still get reset.

Categories

Resources