How do I get the longitude and latitude from the searched location with the google maps place search box api.
Im using the same code as the google demo - https://developers.google.com/maps/documentation/javascript/examples/places-searchbox
function GetLatlong() {
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('textboxid').value;
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
}
});
}
You can use the above function which will give you the latitude and longitude for the area entered by user.
The code on the link you provide shows a function to do when a search is entered. First, it creates an empty array of markers (the pins you see on the map once you perform a search).
So, check the function starting with:
google.maps.event.addListener(searchBox, 'places_changed', function() {
You'll see later on that a marker has been created (there's even a comment):
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
So, on place.geometry.location you have a Google Maps Location object. You could use place.geometry.location.lat() and place.geometry.location.lng().
Check here, too: https://stackoverflow.com/a/15315483/1012139
From the docs:
// Autocomplete Options
var defaultBounds = new google.maps.LatLngBounds();
var options = {
types: ['(cities)'],
bounds: defaultBounds
};
// get DOM's input element
var input = document.getElementById('location_address');
// Make Autocomplete instance
var autocomplete = new google.maps.places.Autocomplete(input, options);
// Listener for whenever input value changes
autocomplete.addListener('place_changed', function() {
// Get place info
var place = autocomplete.getPlace();
// Do whatever with the value!
console.log(place.geometry.location.lat());
});
HTML:
<input type="text" id="address" name="address" value=""> //Autocomplete input address
<input type="hidden" name="s_latitude" id="s_latitude" value="" /> //get latitude
<input type="hidden" name="s_longitude" id="s_longitude" value="" /> //get longitude
Javascript:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initMap"
async defer></script>
<script>
var input = document.getElementById('address');
var originLatitude = document.getElementById('s_latitude');
var originLongitude = document.getElementById('s_longitude');
var originAutocomplete = new google.maps.places.Autocomplete(input);
originAutocomplete.addListener('place_changed', function(event) {
var place = originAutocomplete.getPlace();
if (place.hasOwnProperty('place_id')) {
if (!place.geometry) {
// window.alert("Autocomplete's returned place contains no geometry");
return;
}
originLatitude.value = place.geometry.location.lat();
originLongitude.value = place.geometry.location.lng();
} else {
service.textSearch({
query: place.name
}, function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
originLatitude.value = results[0].geometry.location.lat();
originLongitude.value = results[0].geometry.location.lng();
}
});
}
});
</script>
navigator.geolocation.getCurrentPosition(success => {
console.log(success) // `have the lat and long`
}, failure =>{
//`enter code here if failed`
});
Related
I am making the website with food ordering and delivering module. For that I am using Mapbox and here first i want to select the store-address location with longitude and latitude which i want to select from my addresses table.I dont know how to display the address-location with the longitude and latitude of specific store-address and show with the marker.
Here is the code of the Controller function for getting the value of longitude and latitude of specific address with id :
public function mapofstore($id)
{
$data = DB::Table('addresses')->select('longitude','latitude')->where('id',$id)->get();
// dd($data);
return view('MainAdmin.frontend.reports.storelocation',compact('data'));
}
Here is the code of javascript reference from the official doc of Mapbox:
<div class="container">
<div class="map-area">
<div id='map' style=" width:100%; height: 500px; border: solid;border-color: #1e828de8;border-radius: 1%;"></div>
<pre id="info"></pre>
</div>
</div>
<script>
mapboxgl.accessToken = 'My_MapBox_Api';
var map = new mapboxgl.Map({
container: 'map',
style: 'Style_URL'
});
navigator.geolocation.getCurrentPosition(successLocation,errorLocation,{
enableHighAccuracy: true
})
function successLocation(){
console.log(position)
}
function errorLocation(){
}
function getReverseGeocodingData(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
// This is making the Geocode request
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'latLng': latlng }, (results, status) =>{
if (status !== google.maps.GeocoderStatus.OK) {
alert(status);
}
// This is checking to see if the Geoeode Status is OK before proceeding
if (status == google.maps.GeocoderStatus.OK) {
console.log(results);
var address = (results[0].formatted_address);
}
});
}
function onClick(event){
document.getElementById('lat').value = event.latlng.lat;
document.getElementById('lng').value = event.latlng.lng;
var group = L.featureGroup();
group.id = 'group';
var p_base = L.circleMarker([event.latlng.lat ,event.latlng.lng], {
color: '#fff',
fillColor: '#6a97cb',
fillOpacity: 1,
weight: 1,
radius: 6
}).addTo(group);
map.addLayer(group);
}
// function START for getting lng,lat of current mouse position----------------
map.on('mousemove', (e) => {
document.getElementById('info').innerHTML =
// `e.point` is the x, y coordinates of the `mousemove` event
// relative to the top-left corner of the map.
JSON.stringify(e.point) +
'<br />' +
// `e.lngLat` is the longitude, latitude geographical position of the event.
JSON.stringify(e.lngLat.wrap());
});
// function END for getting lng,lat of current mouse position------------------
// function START for getting current location----------------
map.addControl(new mapboxgl.NavigationControl());
map.addControl(
new mapboxgl.GeolocateControl({
positionOption:{
enableHighAccuracy:true
},
trackUserLocation:true
}));
// function END for getting current location------------------
// function for Direction and Pointing of one Point-----------
map.addControl(
new MapboxDirections({
accessToken: mapboxgl.accessToken
}),
'top-left'
);
const addMarker = () => {
const marker = new mapboxgl.Marker()
// const minPopup = new mapboxgl.Popup({closeButton: false, closeOnClick: false})
minPopup.setHTML("")
marker.setPopup(minPopup)
marker.setLngLat([36.67981,22.10816])
marker.addTo(map)
marker.togglePopup();
}
map.on("load",addMarker)
$.getJSON("https://jsonip.com?callback=?", function (data) {
var ip = data;
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// console.log(url);
$.ajax({
url : '{{URL::to('updateip')}}' + '/' + id,
type: 'POST',
data: {_token: CSRF_TOKEN,
"ip": ip,
"id": id
},
dataType: 'json',
success: function(response){
}
});
});
// function for Direction and Pointing of one Point-----------
function show_marker(Lng,Lat,date,In,Out,hname,hin,hout)
{
const marker = new mapboxgl.Marker({ "color": "#b40219" })
// const minPopup = new mapboxgl.Popup({closeButton: false, closeOnClick: false})
minPopup.setHTML("<strong><b>IN n OUT DATE:</b><br>"+date+"<br><b>IN n OUT TIME:</b><br>"+In+"-"+Out+"<br><b>HOTEL NAME:</b><br>"+hname+"<br><b>HOTEL IN n OUT:</b><br>"+hin+"-"+hout+"</strong>")
// marker.setPopup(minPopup)
marker.setLngLat([Lng,Lat])
// marker.setRotation(45);
marker.addTo(map)
}
const popup = new mapboxgl.Popup({ closeOnClick: false })
.setLngLat([-96, 37.8])
.setHTML('<h1>Hello World!</h1>')
.addTo(map);
</script>
You already have made addMarker function. You just have to pass the lat long there from your data collection. I am assuming that you are using the blade template only. In blade template, you can get your data to javascript variable easily.
var data = <?php echo json_encode($data); ?>
Then you have to parse encoded data into new variables using
var newData = JSON.parse(data);
After that, you can use your newData to get the lat long which you can pass in your function and use it.
var lat = newData[0].latitude
var lng = newData[0].longitude
const addMarker = (lat, lng) => {
const marker = new mapboxgl.Marker()
minPopup.setHTML("")
marker.setPopup(minPopup)
marker.setLngLat([lng,lat])
marker.addTo(map)
marker.togglePopup();
}
// calling add marker
addMarker(lat, lng);
Reference for passing data to javascript. Please note that these methods are different in different Laravel versions.
This question already has answers here:
Address validation using Google Maps API
(10 answers)
Closed 7 years ago.
I have wrote following example:
http://jsfiddle.net/214190tj/1/
html:
<label for="searchTextField">Please Insert an address:</label>
<br>
<input id="searchTextField" type="text" size="50">
<input type="submit" value="is valid">
js:
var input = document.getElementById('searchTextField');
var options = {componentRestrictions: {country: 'us'}};
new google.maps.places.Autocomplete(input, options);
Now it is working good but I need to check that uset didn't type something like "dsgfdsgfjhfg" when button clicks.
Please help to improve my code.
P.S.
this approximately make what I want but it executes in callback. I need a function which returns true or false.
function codeEditAddress(id) {
var address = document.getElementById('address' + id).value;
isValid = undefined;
geocoder.geocode({ 'address': address}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
$("#mapLat" + id).val(results[0].geometry.location.lat());
$("#mapLng" + id).val(results[0].geometry.location.lng());
if (marker) {
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.setMap(map);
isValid = true;
} else {
isValid = false;
}
});
}
You're going to have to re-design your address checker function so that you pass in a callback function. Returning a value from an asynchronous operation inherently does not make sense. You'll want something like this:
function codeEditAddress(id, callback) {
var address = document.getElementById('address' + id).value;
geocoder.geocode({ 'address': address}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
$("#mapLat" + id).val(results[0].geometry.location.lat());
$("#mapLng" + id).val(results[0].geometry.location.lng());
if (marker) {
marker.setMap(null);
}
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.setMap(map);
callback(true);
} else {
callback(false);
}
});
}
To call this function:
codeEditAddress(id, function(isValid) {
if (isValid) {
// submit form, do whatever
}
else {
// show error message, etc
}
});
This is the code I am working from:
http://jsfiddle.net/njDvn/75/
var GeoCoded = {done: false};
$(document).ready(function(){
console.log('ready!');
autosuggest();
console.log($('#myform input[type="submit"]'));
$('#myform').on('submit',function(e){
if(GeoCoded.done)
return true;
e.preventDefault();
console.log('submit stopped');
var geocoder = new google.maps.Geocoder();
var address = document.getElementById('location').value;
$('#myform input[type="submit"]').attr('disabled',true);
geocoder.geocode({
'address': address
},
function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latLng = results[0].geometry.location;
$('#lat').val(results[0].geometry.location.lat());
$('#lng').val(results[0].geometry.location.lng());
//if you only want to submit in the event of successful geocoding, you can only trigger submission here.
GeoCoded.done = true;
$('#myform').submit();
} else {
console.log("Geocode was not successful for the following reason: " + status);
//enable the submit button
$('#myform input[type="submit"]').attr('disabled',false);
}
});
});
});
This works how I want BUT, I wanted to complete the geocode when someone clicks on the autocomplete. So, when they type something and click on a suggestion from the autosuggest list, it actually completes the geocode call when the click the result.
If anyone could tell me if this is possible I would really appreciate it, because I havent been able to figure out how to do it myself.
Autocomplete incorporates geocoding automatically. Example here.
Edit:
Here is the gist of that example:
The key lines for creating the autocomplete control are:
var input = document.getElementById('searchTextField');
var options = {
types: [],
componentRestrictions: {country: 'us'}
};
var autocomplete = new google.maps.places.Autocomplete(input, options);
You also need to load the Places library:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
and in your HTML:
<input id="searchTextField" type="text" size="50" value="">
By the way, you don't "add autocomplete to the geocoder".The Places Autocomplete class includes geocoding capabilities.
I have a form on my Jquery Mobile page where the user can insert a start-location and a destination.
These values will be saved inside the localstorage.
Now I'm trying to manipulate the input like this:
when you type (for instance) 'current' in the input-box, the user's location will be placed inside the localstorage-database instead of the word 'current'.
I already made this script to get the user's location:
var geocoder;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(successFunction, errorFunction);
}
//Get the latitude and the longitude;
function successFunction(position) {
var lat = position.coords.latitude;
var lng = position.coords.longitude;
codeLatLng(lat, lng)
}
function errorFunction(){
alert("Geocoder failed");
}
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeLatLng(lat, lng) {
var latlng = new google.maps.LatLng(lat, lng);
geocoder.geocode({'latLng': latlng}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log(results)
if (results[1]) {
//formatted address
document.getElementById('formatedAddress').innerHTML = results[0].formatted_address;
//find country name
for (var i=0; i<results[0].address_components.length; i++) {
for (var b=0;b<results[0].address_components[i].types.length;b++) {
//there are different types that might hold a city admin_area_lvl_1 usually does in come cases looking for sublocality type will be more appropriate
if (results[0].address_components[i].types[b] == "administrative_area_level_1") {
//this is the object you are looking for
city= results[0].address_components[i];
break;
}
}
}
}
}
}
);
}
The 2 input fields:
<label for="start">Startlocation:</label>
<input type="text" name="start" value="" id="start"/>
<label for="destination">Destination:</label>
<input type="text" name="destination" value="" id="destination"/>
I'm very new to javascript and jQuery and I can't seem to find a solution to my problem.
I hope someone could help me. Thanks!
var start = document.getElementById('start').value;
if (start == 'current') {
//set lat & long to current
}
else {
//read lat & long from input fields
}
This bit of logic may prove to be what you're after - however I do tend to agree with logical Chimp that UX is very important, and a "use current location" button may prove to be more useful to the user.
I have a javascript.In it i have a code which displays the latitude and longitude of number of locations in pune.
The latitude and longitude gets displayed in an alertbox.
When i write it in a document.write() method it gives error.After that i used
"document.body.appendChild( document.createTextNode( latitude ) );
document.body.textContent = latitude;"
but it displays a single value.I want that all the latitude and longitude should be displayed in single page.Please guide me.
My code is here:
function myfun()
{
document.getElementById("demo").innerHTML="My Javascript";
var geocoder=new google.maps.Geocoder();
var i=0;
var address=new Array();
address[0]="kothrud pune";
address[1]="bharti vidyapeeth";
for(i=0;i<address.length;i++)
{
geocoder.geocode( { 'address': address[i]}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
//alert(latitude);
//alert(longitude);
//document.write(latitude);
document.body.appendChild( document.createTextNode( latitude ) );
document.body.textContent = latitude;
//document.body.appendChild( document.createTextNode( longitude ) );
//document.body.textContent = longitude;
}
});
}
}
Include jquery, it's easier to use for manipulating the DOM.
Get the div or other element you want to add the values to and use jQuerys html method to set the latitude and longitude values as text to the element.
$('#YourElementIdHere').html(latitude + ', ' + longitude);
You want to write the longitude and latitude to the screen? I would use jquery and create a div.
<script>
....
$("#Longlat").html(YourlongandLat);
</script>
....
<div id ="LongLat"></div>