Using Geocorder result in other function in VUe - google-maps

i try to use the result of Geocode Lag Long, but i can't use out of the function. How can i use the result in other function in Vue?
Why i can't use "this.markerCoordinates" in other functions?
getLocation : function (address){
const element = document.getElementById(this.mapName);
var local;
// geocoder API (pega o endereço)
var geocoder = new google.maps.Geocoder(address);
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();
// I WANT USE THIS IN OHTER FUNCTION
this.markerCoordinates = [{"latitude" :latitude , "longitude" : longitude}]
callback( this.markerCoordinates[0])
}
var mapCentre = this.markerCoordinates[0]
var options = {
zoom : 16,
center: new google.maps.LatLng(mapCentre.latitude , mapCentre.longitude)
}
this.options = options;
this.map = new google.maps.Map(element, options);
this.markerCoordinates.forEach((coord) => {
const position = new google.maps.LatLng(coord.latitude, coord.longitude);
const marker = new google.maps.Marker({
position,
map: this.map
});
});
});
},
in other functions is return undefined

Define a data element for your coordinates in your component, see here for an example: data() {return { markerCoordinates: undefined } }
In your getLocation function, you need a closure that points to the enclosing Vue instance , like this let vm = this. See here, e.g.
In the callback, use this variable to access the data element: vm.markerCoordinates = [{"latitude" :latitude , "longitude" : longitude}]
Access the it in the template simply by using markerCoordinates and in other methods of your component with this.markerCoordinates

Related

google maps click event isn't reading objects from data

I'm trying to get latitude and longitude by clicking on map then I use them to get formatted address from google maps API and finally I want to persist lat, lng and formatted address in my object "station" declared in data
data() {
return {
station: {},
mapName: this.name + "-map",
lat: Number,
lng: Number,
Fulladdress: String
};
} ,
mounted() {
const element = document.getElementById(this.mapName);
const options = {
zoom: 14,
center: new google.maps.LatLng(51.501527, -0.1921837)
};
const map = new google.maps.Map(element, options);
google.maps.event.addListener(map, "click", function(event) {
this.lat = event.latLng.lat();
this.lng = event.latLng.lng();
axios
.get(
"https://maps.googleapis.com/maps/api/geocode/json?latlng=" +
this.lat +
"," +
this.lng +
"&key=APIKEY"
)
.then(resp => {
var fulladdress;
console.log(resp.data.results[0].formatted_address);
fulladdress = resp.data.results[0].formatted_address;
this.Fulladdress = fulladdress;
//persist lat, lng and formatted address in my object station
this.station.address = this.Fulladdress;
this.station.lat = this.lat;
this.station.lng = this.lng;
})
.catch(e => {
console.log(e);
});
});
}
The context is changing. Inside the click handler, the this is not referring to the Vue instance, but something else (it depends on how google maps does it, but it could be window or the map instance).
To have the this be the Vue instance, use arrow functions instead.
Change from:
google.maps.event.addListener(map, "click", function(event) {
To:
google.maps.event.addListener(map, "click", (event) => {

Google Maps API Geocode - return GPS coordinations [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got this code:
var get_lat = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lat is: '+ results[0].geometry.location.lat());
return results[0].geometry.location.lat();
}
});
}
var get_lng = function(address) {
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
console.log('lng is: '+ results[0].geometry.location.lng());
return results[0].geometry.location.lng();
}
});
}
In console it prints the coordinates I need, but the return value is always undefined:
I use it in classic initialize for Google Maps like this:
function createMarker(latlng) {
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
}
function initialize() {
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(49.210366,15.989588)
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
var gps_lat = get_lat(address);
var gps_lng = get_lng(address);
console.log('GPS lat: ' + gps_lat); // logs "undefined"
console.log('GPS lng: ' + gps_lng); // logs "undefined"
var marker = createMarker({lat: gps_lat}, lng: gps_lng});
}
$(window).on("load", function (e) {
initialize();
});
Do you have any idea why the function consoles the right value but it doesn't return anything?
For GMAP API I use this script: http://maps.google.com/maps/api/js?sensor=false&libraries=geometry
You have the return inside an anonymous function that you pass to geocoder.geocode, all in yet another function (get_lat/get_lng). get_lat/get_lng themselves don't have a return statement, and thus return undefined.
Furthermore, geocoder.geocode will call your anonymous function asynchronously. Which means that there is no chance for get_lat/get_lng to get hold of the return value and return it where get_lat/get_lng was called.
One solution (the simplest one) is to put the createMarker code in the callback for geocoder.geocode. Also, in this case you will have to merge your two get_lat/get_lng functions. Example:
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var gps_lat = results[0].geometry.location.lat()
var gps_lng = results[0].geometry.location.lng();
console.log('lat is ' + gps_lat + '. lng is ' + gps_lng);
var marker = createMarker({lat: gps_lat, lng: gps_lng});
return results[0].geometry.location.lat();
}
});
You have to wait until Google API gives response. So write a logic to create marker in callback function of Google API as shown below.
var getLatLng = function (address)
{
geocoder.geocode({ 'address': address }, function (results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
var location = results[0].geometry.location;
// Create marker once you get response from Google
createMarker({ lat: location.lat(), lng: location.lng() });
}
});
}
and call that function as shown below
function initialize()
{
var myOptions =
{
zoom: 8,
center: new google.maps.LatLng(49.210366, 15.989588)
}
map = new google.maps.Map(document.getElementById("map"), myOptions);
var address = "Correct address that console.logs the correct GPS coordinations in function definitions above";
// Old code ------------------------------------------------
//var gps_lat = get_lat(address);
//var gps_lng = get_lng(address);
//console.log('GPS lat: ' + gps_lat); // logs "undefined"
//console.log('GPS lng: ' + gps_lng); // logs "undefined"
//var marker = createMarker({ lat: gps_lat, lng: gps_lng });
// ----------------------------------------------------------
// New code
getLatLng(address);
}
and you will get marker on a map

retrieving latitude and longitude from database(db2) and show in map in IBM worklight

I have saved latitude and longitude in database(db2).I want to use them to show their location in map.I am working with IBM Worklight and as database I am using DB2.
My problem is I can retrieve value from database,store it in a variable but could not be able to pass the value in the function of map where it can be used as latitude and longitude.
Any positive help would be appreciated.Thanks in advance.
My approach:
CODE:
var mylat;
var mylon;
var clat;
var clon;
function maplo() {
//database value,I have stored them in a text input type
clat=$("#lati").val();
clon=$("#long").val();
}
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;
mylat=position.coords.latitude;
mylon=position.coords.longitude;
}
function success(position) {
//reload();
maplo();
showPosition(position);
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('article').appendChild(mapcanvas);
var flat=clat;
var flon=clon;
alert("custom latitude is : "+flat);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var coords1 = new google.maps.LatLng(flat, flon);
var options = {
zoom: 16,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
var geolocation = new google.maps.Marker({
position: coords1,
map: map,
title: 'Your car location',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
function searchcarl()
{
var a=$("#searchcar").val();
var invocationData={
adapter:'park',
procedure :'procedure4',
parameters:[a]
};
var options={
onSuccess:success6,
onFailure:fail6
};
WL.Client.invokeProcedure(invocationData, options);
}
function success6(result){
if((result.invocationResult.resultSet.length)>0)
{
alert("location fetching!");
var I=result.invocationResult.resultSet[0].LAT;
var J=result.invocationResult.resultSet[0].LON;
$("#lati").val(I);
$("#long").val(J);
}
else{
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function fail6()
{
alert("fail6");
}
I will update the code as follows:
// create a map global variable
var map;
function initMap(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('body').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom : 16,
center : coords,
mapTypeControl : false,
navigationControlOptions : {
style : google.maps.NavigationControlStyle.SMALL
},
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position : coords,
map : map,
title : "You are here!"
});
}
// adds a marker to the map
function addCarLocationMarker(lat, lng) {
var coords = new google.maps.LatLng(lat, lng);
var geolocation = new google.maps.Marker({
position : cords,
map : map,
title : 'Your car location',
icon : 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// once you know the user location, init the map
initMap(position);
});
} else {
alert('Geo Location is not supported');
}
function searchcarl() {
var a = $("#searchcar").val();
var invocationData = {
adapter : 'park',
procedure : 'procedure4',
parameters : [ a ]
};
var options = {
onSuccess : adapterSuccess,
onFailure : adapterFailed
};
WL.Client.invokeProcedure(invocationData, options);
}
function adapterSuccess(result) {
if ((result.invocationResult.resultSet.length) > 0) {
alert("location fetching!");
var I = result.invocationResult.resultSet[0].LAT;
var J = result.invocationResult.resultSet[0].LON;
// add the marker directly to the map
addCarLocationMarker(I, J);
}
else {
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function adapterFailed() {
alert("adapter invocation failed");
}
Like Idan mentioned, it's not a good idea to store the coordinates in text boxes to then use the text boxes as the source of the coordinates.
You should add the marker directly after you received the coordinates from the adapter. In this case I created a separate function initMap to initialize the map and center it on the current user's location. It is a good idea to make your functions smaller to perform one single task.
I removed some function that I thought you didn't need or were duplicating functionality namely maplo, getLocation and showPosition.

routes are not defined when calling calcRoute with params (latLng) - Google Maps

I need to call pass params to calcRoute() on click, what I am doing is:
function calcRoute(source,destt) {
var start = new google.maps.LatLng(source);
var end = new google.maps.LatLng(destt);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
Click Event:
$('#go').click(function(){
var from= "24.942834,67.121237";
var to = "24.944908,67.124491";
calcRoute(from,to);
});
It's returning the status with ZERO_RESULT
It was working fine when I hard coded lat n lng in calcRoute(), i.e
var start = new google.maps.LatLng(24.942834,67.121237);
var end = new google.maps.LatLng(24.944908,67.124491);
Thanks for any Help.
Direct string will not work as LatLng object you have to convert "24.942834,67.121237" to google.maps.LatLng to make it work.
$('#go').click(function(){
var from= new google.maps.LatLng(24.942834,67.121237);// convert it to latlng object
var to = new google.maps.LatLng(24.944908,67.124491);
calcRoute(from,to);
});
if you have "24.942834,67.121237" then you can use it like this:
var str="24.942834,67.121237";
var latlng=str.split(',')
var to = new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));

Google Maps Directions dragged polyline coordinates reset after extending the route

Hey guys, the function of this code is described below.
there are some predefined functions below i.e getMapOption and others
function initialize(){
var divCalcDis = $('divCalcDis');
var pdist = $('pdist');
var pTimeTaken = $('pTimeTaken');
var txtLatLon = $('divLatLon');
var lblDistance = $('lblDistance');
var mapOption = mapHandler.getMapOption(that.LonLatCoordinates[0], 15, "Default");
map = mapHandler.getMap('map_canvas', mapOption);
var renderOption = { draggable: true };
directionsDisplay = new google.maps.DirectionsRenderer(renderOption);
directionsDisplay.setMap(map);
google.maps.event.addListener(directionsDisplay, 'directions_changed', function () { for (i = 0; i < directionsDisplay.directions.routes.length; i++) {
//getting latlon
txtLatLon.innerHTML = "";
console.log(directionsDisplay.directions.routes[i].overview_path.length);
var latLng = directionsDisplay.directions.routes[i].overview_path[k];
var latLng = directionsDisplay.directions.routes[i].overview_path[directionsDisplay.directions.routes[i].overview_path.length - 1].toString();
latLng = latLng.split('(')[1];
latLng = latLng.split(')')[0];
latLng = latLng.split(' ');
latLng = latLng[0] + latLng[1];
txtLatLon.innerHTML += latLng;
}
});
startMap();
}
function startMap() {
var i=0;
google.maps.event.addListener(map, 'click', function (event) {
i++;
if(i === 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
that.origin = event.latLng; //comma seperated values of lat,lon
}
else if(i > 1){
mapHandler.setMarker(event.latLng, map, "http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png", null, null, null, that.permanentMarkers, false);
if (i === 2) {
that.dest = event.latLng; //comma seperated values of lat,lon
}
else if (i > 2) {
that.wayPTs.push({
location: that.dest,
stopover: true
});
that.dest = event.latLng;
}
that.calcRoute();
}});
};
function calcRoute() {
var divCalcDis = stringHandler._id('divCalcDis');
var pdist = stringHandler._id('pdist');
var pTimeTaken = stringHandler._id('pTimeTaken');
var txtLatLon = stringHandler._id('divLatLon');
txtLatLon.innerHTML = "";
if (!that.wayPTs.length > 1) {
this.wayPTs = null;
}
var request = this.directionsRequest(this.origin,this.dest,google.maps.DirectionsTravelMode.DRIVING,this.wayPTs,false,true,true,google.maps.DirectionsUnitSystem.METRIC);
that.directionsResponse.route(request, function (response, status) {
//console.log(response);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
};
**
I am making a project using Google Maps API V3 Directions library in which i am creating a route when a user click some place on the map
Here is a screenshot**
Now when i drag the direction drawn line it works smoothly and giving me the latitude and longitude correctly.
Here is a screenshot
But the Problem is when i click on anyother place on the map(after dragging) the waypoint refreshes and i get the old without drag route with the next stop as you can see below
Here is a Screenshot
How to save the latLon of the waypoint so they are available after creation of new points Thx
You need to push the coordinates into the route array so they will always be available. So push when you drag and push when you click. May be this can be of assistance to you. Best of luck.