Combine variables in a string, reverse geocoding - javascript - javascript

I try to get back the adress of the point where the "user" clicks on the "google map" I have implemented on my website.
I copied the source code form developers.google.com and made a view adaptations. In the source from google, you get the "latlng" by an input field. I get it by a "event".
In my "geocode-function" I sum my "lat" and "lng" parameters together to what they would have looked like if they came out of the input field.
Here is the code:
// Set variables
var clicklat;
var clicklng;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow;
// Listen for click on map
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
clicklat = parseFloat(event.latLng.lat());
clicklng = parseFloat(event.latLng.lng());
geocodeLatLng(geocoder, map, infowindow);
});
// Geocode function
function geocodeLatLng(geocoder, map, infowindow) {
var input = "#{clicklat},#{clicklng}"
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
Now, the problem I have is that console.log(input); gives back: #{clicklat},#{clicklng}. Why, the heck, my variables get not implemented there?

It looks like you are trying to usea "jade" and is not working?
Anyway Here is a way to make it work:
// Set variables
//var clicklat;
//var clicklng;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow;
// Listen for click on map
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
//clicklat = parseFloat(event.latLng.lat());
//clicklng = parseFloat(event.latLng.lng());
geocodeLatLng(geocoder, map, infowindow, event.latLng); //I add this as a parameter
});
// Geocode function
function geocodeLatLng(geocoder, map, infowindow, thelocation) {
// var input = "#{clicklat},#{clicklng}"
// var latlngStr = input.split(',', 2);
// var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': thelocation}, function(results, status) {
if (status === 'OK') {
if (results[1]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: results[1].geometry.location,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}

Related

Why is my map not displaying the place name in the map after getting the current location?

I have made a map with getting the current location,inside the getPosition is getting also the place name which I also made a reverse geocoding that returns the place name from a coordinate, I wonder what's wrong my code that it did not return the place name and even the marker with my code for reverse geocoding.
In the console I get this
<p id="curr" style="">current lat lng</p>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}

Why is my reverse geocoding not working and displaying?

I have a nearby search map, in every open of this map page, it returns the current position, now When I get the current position by coordinates, I want to reverse geocode it into an address name, the problem is I modified my code from this source: https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse
with
<script>
function getPosition() {
navigator.geolocation.getCurrentPosition(position => {
currentLatLon = [position.coords.latitude, position.coords.longitude];
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(
document.getElementById('map'), {
center: new google.maps.LatLng(...currentLatLon),
zoom: 20
});
var geocoder = new google.maps.Geocoder();
service = new google.maps.places.PlacesService(map);
document.getElementById("curr").innerHTML=currentLatLon;
document.getElementById("address").value=currentLatLon;
geocodeLatLng(geocoder,map,infowindow);
});
}
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('curr').value;
var latlngStr = input.split(',');
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
</script>
this should return the place name in the map which is like the source code I copied from above
https://developers-dot-devsite-v2-prod.appspot.com/maps/documentation/javascript/examples/geocoding-reverse, what could be wrong in my modification? I have an error in the console when I run my modified code, error in the console
Here's my full code without the api key: https://pastebin.com/BhEqRsq0
You set the lat/lng coordinates to the <p> element's innerHTML, not to its (unsupported) value which is why it returns undefined:
document.getElementById("curr").innerHTML = currentLatLon;
So change this code:
var input = document.getElementById('curr').value;
to the following:
var input = document.getElementById('curr').innerHTML;
I just ran your web app on my end and reverse geocoding works fine after the above fix. So hope this helps!

Use Reverse Geocoding in Vue.js

I'm working on a project which track GPS locations and should display in Google map as points. Therefore I use Reverse Geocoding.
I just put below code inside methods: in my Component.
initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 8,
center: {lat: 40.731, lng: -73.997}
});
var geocoder = new google.maps.Geocoder;
var infowindow = new google.maps.InfoWindow;
document.getElementById('submit').addEventListener('click', function() {
this.geocodeLatLng(geocoder, map, infowindow);
});
},
geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function(results, status) {
if (status === 'OK') {
if (results[0]) {
map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
infowindow.setContent(results[0].formatted_address);
infowindow.open(map, marker);
} else {
alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
Also I put below code in app.blade.php
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY&callback=initMap">
</script>
My problem is when I use callback in parameter the initMap function is not identified. Therefore map is not loading on my view. How should I use it? and also should I need to use axios.get(my_url_here) to do this? I'm stuck in this case. If anyone can consider and help me for this matter would be grateful.

How to populate a string array by clicking on the map in JavaScript?

I want to gather information as I click on the map in JavaScript. I'm using Google Maps API. As I right click on the map a reverse Geocode tool works and gets the information of the point clicked.
What I want to do is as I clicked on the map I want to see these Geocoded points names and some attributes in a list.
Is it even possible ?
here I'm sharing some of my code ;
This is clicking and getting coordinates ;
google.maps.event.addListener(map, "rightclick", function (event) {
var lat = event.latLng.lat();
var lng = event.latLng.lng();
alert(markersinfo);
document.getElementById("latlng").value = lat.toFixed(5) + ', ' + lng.toFixed(5);
geocodeLatLng(geocoder, map, infowindow);
});
Here is geocoding ;
function geocodeLatLng(geocoder, map, infowindow) {
var input = document.getElementById('latlng').value;
var latlngStr = input.split(',', 2);
var latlng = {lat: parseFloat(latlngStr[0]), lng: parseFloat(latlngStr[1])};
geocoder.geocode({'location': latlng}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
if (results[1]) {
//map.setZoom(11);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
markersinfo.push(marker);
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
I've tried to create an array called markersinfo[] and tried to push markers in to this array but I've realized that I'm just sending objects to array but not the informations. I need Geocode string , latitude and longitude of each clicked point in this markersinfo[] array.
So, instead of google.maps.Marker objects you would like to save lat, lng and address properties in markersinfo array, right? If so, the below example shows how to accomplish it:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {
lat: -28.643387,
lng: 153.612224
},
mapTypeControl: true
});
var infowindow = new google.maps.InfoWindow({
content: ''
});
var geocoder = new google.maps.Geocoder();
var markersinfo = [];
google.maps.event.addListener(map, "rightclick", function(event) {
geocodeLatLng(geocoder, event.latLng,
function(results) {
if (results[0]) {
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
infowindow.setContent(results[1].formatted_address);
infowindow.open(map, marker);
markersinfo.push({
'address': results[0].formatted_address,
'lat': event.latLng.lat(),
'lng': event.latLng.lng()
}); //save info
document.getElementById('output').innerHTML = JSON.stringify(markersinfo);
} else {
window.alert('No results found');
}
},
function(status) {
window.alert('Geocoder failed due to: ' + status);
});
});
}
function geocodeLatLng(geocoder, latLng, success, error) {
var location = {
lat: latLng.lat(),
lng: latLng.lng()
};
geocoder.geocode({
'location': location
}, function(results, status) {
if (status === google.maps.GeocoderStatus.OK) {
success(results);
} else {
error(status);
}
});
}
html,
body {
height: 220px;
margin: 0;
padding: 0;
}
#map {
height: 220px;
}
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?signed_in=false&callback=initMap" async defer>
</script>
<div id='output' />
You can gather your info in the same area where you're putting info in your infowindow. Just save your lat / long, etc to a string or array. You haven't been very clear about what content should be shown (other than lat / long), or what is clicked to trigger the display. So this code will need to be adjusted to suit your specific needs.
Example:
var contentString = "";
if (results[1]) {
//...
var contentString += "Location: " + latlng + "<br />";
}
//perhaps add trigger this on an event, depending on what you want.
$('#myDiv').append(contentString);
And then your div to hold the content:
<div id="myDiv"></div>

Update Marker Position Google Maps V3

I am quite a novice with javascript stuff and am currently faking it till i make it lol and now ive come across a small hill that i'm struggling to get over :S.
Currently my script finds the users location and adds a pin to the map while copying LatLon to some form fields.
In addition to just zooming in on the users location i would like them to have the ability to add a custom address which is entered into a text field, geocoded and then updates the current pin on the map.
This all works, although it adds an additional pin to the map rather than updating the current pin.
I am unsure how to pass the value from the address geocoding function back into the original pin / or do i delete the original pin and add a new pin. I'm sure i can reuse some functions as well... i don't think my code is terribly efficient :/
Any way i hope a guru out there can help me out
Cheers
Nick
var geocoder;
var map;
var pos;
function initialize() {
geocoder = new google.maps.Geocoder();
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var address = document.getElementById("address").value;
var initialLocation;
var myOptions = {
zoom: 12,
center: initialLocation,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
map: map,
position: pos,
title: 'Location found using HTML5.',
draggable: true
});
var lat = position.coords.latitude
var lng = position.coords.longitude
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
google.maps.event.addListener(marker, "dragend", function(event) {
var lat = event.latLng.lat()
var lng = event.latLng.lng()
var infowindow = new google.maps.InfoWindow({
content: '<b><?php _e('Latitude:');?></b>' + lat + '<br><b><?php _e('Longitude:');?></b>' + lng
});
infowindow.open(map, marker);
google.maps.event.addListener(marker, "dragstart", function() {
infowindow.close();
});
document.getElementById('geo_latitude').value=lat;
document.getElementById('geo_longitude').value=lng;
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else if (google.gears) {
browserSupportFlag = true;
var geo = google.gears.factory.create('beta.geolocation');
geo.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeoLocation(browserSupportFlag);
});
// Browser doesn't support Geolocation
} else {
browserSupportFlag = false;
handleNoGeolocation(browserSupportFlag);
}
function handleNoGeolocation(errorFlag) {
if (errorFlag == true) {
alert("Geolocation service failed.");
initialLocation = newyork;
} else {
alert("Your browser doesn't support geolocation. We've placed you in New York.");
initialLocation = newyork;
}
map.setCenter(initialLocation);
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
//-------------------------------------------------------End initialize
function findAddress(address) {
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 pos = results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
To 'move' your existing marker, you'll wanna make sure its global and then you can just update its position within the findAddress function with something like:
marker.setPosition(results[0].geometry.location);

Categories

Resources