I've generate the api key on https://console.cloud.google.com. and then i use that key in my code like
"https://maps.googleapis.com/maps/api/js?key=MyKey&callback=initMap" in my script tag.
when i visit the generated url then that stated an error:
You must use an API key to authenticate each request to Google Maps
Platform APIs. For additional information, please refer to
http://g.co/dev/maps-no-account
function initMap(){
//
}
var x = document.getElementById('output');
function getLocation() {
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
x.innerHTML = "Browser Not Compatible";
}
}
function showPosition(position) {
x.innerHTML = "latitude = "+position.coords.latitude;
x.innerHTML += "<br>";
x.innerHTML += "longititude = "+position.coords.longitude;
var locAPI = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude+","+position.coords.longitude+"&sensor=true";
x.innerHTML = locAPI;
}
<div id="wrapper">
<button id="location-button"
onclick="getLocation()">Get User Location</button>
<div id="output"></div>
</div>
can some body please help me to resolve this issue
I think you missed the key param in showPosition(). Can you please try this:
function showPosition(position) {
x.innerHTML = "latitude = "+position.coords.latitude;
x.innerHTML += "<br>";
x.innerHTML += "longititude = "+position.coords.longitude;
var locAPI = "http://maps.googleapis.com/maps/api/geocode/json?latlng="+position.coords.latitude+","+position.coords.longitude+"&sensor=true&key=your_key";
x.innerHTML = locAPI;
}
Hope this helps!
Related
the GPS code works fine as long as i take out the php code.
is there some kind of overlapping interference between php and javascript
any help would be greatly appreciated
<?php
// Initialize the session
session_start();
// Check if the user is logged in, if not then redirect him to login page
if(!isset($_SESSION["loggedin"]) || $_SESSION["loggedin"] !== true){
header("location: login.php");
exit;
}
else
{
}
?>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
function showPosition(position) { x.innerHTML = "Latitude: " + position.coords.latitude + "<br>Longitude: " + position.coords.longitude;}
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
</script>
Kindly check out your settings for your website/localhost. I think the location is blocked by the your end.
I am trying to use Javascript for finding user location but it is not giving me any value, my code is below
<script>
window.onload = function() {
var startPos;
var geoSuccess = function(position) {
startPos = position;
document.getElementById('startLat').innerHTML = startPos.coords.latitude;
document.getElementById('startLon').innerHTML = startPos.coords.longitude;
};
navigator.geolocation.getCurrentPosition(geoSuccess);
};
</script>
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
The HTML5 Geolocation API allows you to get a user's Latitude/Longitude with some JavaScript (if the browser is compatible, and if the user allows access to his/her location).
You can then reverse-geocode the location to get an address, there are several free reverse-geocoding services other than Google's API.
you can also check out this link How to get geographical location of an IP address in PHP for more understanding
Example:
<script>
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
If you have elements with id's "startLat" and "startLon" in your HTML, it'll work
Just add in HTML:
<p id="startLat"></p>
<p id="startLon"></p>
You can delete this line, actually:
<?php echo "<script> getCurrentPosition('startLat') </script>"; ?>
To use Latitude/Longitude in your PHP you can send the values via JS
In HTML
<script>
function sendData(value) {
var request = new XMLHttpRequest();
request.open('post', 'DESTINATION.PHP', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.send('data=' + value);
}
</script>
Or as a hidden form input
and access in PHP
if(isset($_POST['data'])){
$data = $_POST['data'];
// Do stuff...
}
I'm having trouble figuring why the onClick event is not working inside jsFiddle. The code is working well on the browser, but when try to port it to jsFiddle I lose the ability to fire the onClick events.
My current code is the following:
For the HTML:
<body>
<button id="find-near-btn" onClick="getMylocation()">
Find companies near me
</button>
<button id="mark-pos-btn" onClick="markMyPosition()">
Mark my position
</button>
<div id="mymap"></div>
<div id="output"></div>
</body>
The js:
function initmap(initialLat, initialLong){
output.innerHTML += "<p>Initialized</p>";
if(!initialLat || !initialLat.length){
initialLat = 38.01693;
}
if(!initialLong || !initialLong.length){
initialLong = -8.69475;
}
var mymap = this.mymap = L.map('mymap',{
center: [initialLat, initialLong],
zoom: 15
});
var osmUrl='http://tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
L.tileLayer(osmUrl, osmAttrib).addTo( mymap );
}
function getMylocation(){
output.innerHTML += "<p>Obtaining location.</p>";
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
mymap.setView(new L.LatLng(lat, long), 15);
}, function (error) {
// Get information based on IP
getLatLongByIP();
});
}
}
function getLatLongByIP()
{
$.get("http://ip-api.com/json", function(response) {
handleData(response.lat, response.lon);
}, "jsonp");
}
function handleData(lat, long){
mymap.setView(new L.LatLng(lat, long), 15);
}
function markMyPosition()
{
if(navigator.geolocation){
navigator.geolocation.getCurrentPosition(function (position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
L.marker([lat, long]).addTo(mymap);
}, function (error) {
switch (error.code) {
case error.PERMISSION_DENIED:
output.innerHTML += "<p>User denied the request for Geolocation.</p>";
break;
case error.POSITION_UNAVAILABLE:
output.innerHTML += "<p>Location information is unavailable.</p>";
break;
case error.TIMEOUT:
output.innerHTML += "<p>The request to get user location timed out.</p>";
break;
case error.UNKNOWN_ERROR:
output.innerHTML += "<p>An unknown error occurred.</p>";
break;
}
});
}
}
initialLat = 38.01693;
initialLong = -8.69475;
initmap(initialLat, initialLong);
The fiddle can be found here. When I click any of the buttons I get nothing. Any idea on how can I make this work?
You need to change your JS code to be inside your page's <body> tag. Use the little cog at the top right of the Javascipt panel and choose No wrap - in <body> under Load type. I already tested this and it works.
I am trying to fetch the current location using the geolocation . A month before it was giving correct location but not am getting different location . I have used the same code as below.
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
/*x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
*/ var query = "?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude;
var stateObj = { query: query };
history.pushState(stateObj, "query added", query);
var flag = true;
/*var req = (window.XMLHttpRequest)?new XMLHttpRequest():new ActiveXObject("Microsoft.XMLHTTP");
req.onreadystatechange=function(){if((r.readyState==4)&&(r.status==200)){ console.log('location was sended to server'); }};
req.open("GET","?latitude="+position.coords.latitude+"&longitude="+position.coords.longitude,true);
req.send(null);
*/
}
Another problem is its fetching the latlong based on isp not on IP. So if i use this code using mobile internet ! It gives latlong of another state. Is there any way to make this work again?
I am Building a website useing HTML, CSS and Java script. I am wanting to get the location of the user when page loads. so they do not need to press a button. I was hoping some one can help.
!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to get your coordinates:</p>
<button onclick="getLocation()">Try It</button>
<script>
var x=document.getElementById("demo");
function getLocation(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(showPosition);
}
else{
x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position){
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
Simply call the getLocation()
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
getLocation()
</script>
Fiddle : https://jsfiddle.net/ES4TF/
<p id="demo"></p>
<script>
var x=document.getElementById("demo");
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(showPosition);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function showPosition(position)
{
x.innerHTML="Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
}
getLocation()
</script>
This is an update to the answer above for anyone wanting to do this in react without adding another script. Here is the code in ES2015 format for use with React etc, without needing to use any of the HTML stuff above. Just import the function.
Special thanks to the first post as mine is based off it .
const showPosition = position =>{
let loc = `Latitude:${position.coords.latitude} logitude:
${position.coords.longitude}`
console.log(loc)
return loc
}
const getLocation = () => {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
return false
}
then Just Import the function and Use It
If you want to get the state and zip you can use the google API. Here is the code to get geolocation and the sends to google and then gives you the state, address results. You will need to activate the google geolocation API.
//Docs - https://developers.google.com/maps/documentation/geocoding/intro#ReverseGeocoding
const getData = async (url) => {
let res = await fetch(url)
let json = await res.json()
console.log(json);
return json
}
const showPosition = async position =>{
let loc = `Latitude:${position.coords.latitude} logitude: ${position.coords.longitude}`
let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${position.coords.latitude},${position.coords.longitude}&key={GOOGLE_API_key}`
console.log(loc)
let address = await getData(url)
console.log(`results`,address)
return address
}
const getLocation = async () => {
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(showPosition);
}
return false
}