VueJs only show google map when location is set - javascript

So I'm trying to build a simple app that shows distance to locations on a Google map, from a user's current location.
I'm using Vue.js 1.0 and the vue-google-maps plugin.
I'm trying to center the Google map on user's location, but can only get the map to load if I hard code the longitude and latitude data in my application like this:
export default {
data: function data() {
return {
center:{ lat:28.2328382, lng: -3.298973987232 },
mapBounds: {},
usermarkers: [],
businessmarkers: [],
zoomControl: true,
mapTypeControl: true,
data: {
currentLocation: '',
search: {
lon: '',
lat: '',
unit: '',
order: 'asc',
distance: '',
type: ''
}
},
};
},
My map is rendered here:
<map :center.sync="center" :zoom.sync="zoom" :map-type-id.sync="mapType" :options="{styles: mapStyles}">
<marker v-for="m in usermarkers" :position.sync="m.position">
<info-window :position="center" :content="ifw2text"></info-window>
</marker>
<marker v-for="m in businessmarkers" :position.sync="m.position">
<info-window :position="center" :content="m.ifw2text"></info-window>
</marker>
</map>
Then in the ready function I grab the geolocation of the user via html5 and push the user's marker on to the map.
So what I'm now trying to do is dynamically center the location.
I wrapped my map html in a conditional statement like so
<div v-if="!data.center.lat && !data.center.lng">
<map :center.sync="center" :zoom.sync="zoom" :map-type-id.sync="mapType" :options="{styles: mapStyles}">
<marker v-for="m in usermarkers" :position.sync="m.position">
<info-window :position="center" :content="ifw2text"></info-window>
</marker>
<marker v-for="m in businessmarkers" :position.sync="m.position">
<info-window :position="center" :content="m.ifw2text"></info-window>
</marker>
</map>
</div>
in my data function I leave the center empty
data: function data() {
return {
center:'',
Then my ready function grabs the geolocation builds the center object and sets this.center correctly
ready () {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
let centerObj ={};
centerObj.lat = position.coords.latitude;
centerObj.lng = position.coords.longitude;
this.center = centerObj;
this.usermarkers.push({
position: { lat:this.center.lat, lng: this.center.lng }
});
}.bind(this), function (error) {
if (error.code == error.PERMISSION_DENIED)
alert('Please Enable Location Services');
}.bind(this));
}
},
My console.log show the center.lat and center.lng are set but the map is still not being rendered. Shouldn't vue reload the virtual DOM when data like this is set, thus rendering the map? Am I missing something really simple or going about this the complete wrong way?

Related

DEVExpress DXmap: how to refresh to current location (longitude and latitude)?

When I open my page in google maps with dxmaps, it refreshes automatically to a set location (ML_LATITUDE, ML_LONGITUDE). This corresponds to numbers (like 35.18, 44.12). However, I want the program when to refresh, to remain in the same position that my screen (or cursor) is at.
Here is the relevant code:
markers.push({
location: { lat: oData[item]['ML_LATITUDE'], lng: oData[item]['ML_LONGITUDE'] },
iconSrc: oData[item]['ICON'], //"Content/Icons/map-marker.png",
onClick: function (args) { },
tooltip: {
isShown: fisShown,
text: oData[item]['TOOLTIP']
}
});
}

The map does not work at the beginning of going to the page, but works if it works refresh page in vuejs

The map does not work at the beginning of going to the page, but works if it works refresh page in Vue.js.
Is there any help in this matter?
this code
mounted() {
this.geolocate();
},
methods: {
async geolocate() {
this.getFloatDirections();
this.center = {
lat: this.lat,
lng: this.lng
};
this.coordinates = {
full_name: this.$route.query.name,
lat: this.lat,
lng: this.lng
};
// console.log("typeof(this.center.lat)"+typeof(this.$route.params.lat))
},
getFloatDirections(){
this.lat = parseFloat(this.$route.params.lat);
this.lng = parseFloat(this.$route.params.lng);
},
getPosition: function(marker) {
return {
lat: marker.lat,
lng: marker.lng
};
},
toggleInfo: function(marker) {
this.infoPosition = this.getPosition(marker);
this.infoContent = marker.full_name;
this.infoOpened = true;
}
}
this image before refresh
this image after refresh
Replace mounted() by created()
mounted() is called after DOM has been mounted so you can access the reactive component, templates, and DOM elements and manipulate them.
If you need to know more about vue Lifecycle Hooks.

How to save real-time gps coordinates from geolocation watch into mysql table

I'm fairly new to JS and PHP but I have been working on a large project which has many features for several months and its coming along nicely. The program is largely PHP and JS and will be used on computers in a fleet of vehicles.
One of the program features will use geofences and geolocation.watchPosition to monitor the user's GPS location and send a notification if the user leaves an assigned geofence.
What I need to accomplish is a way to continuously track the user's current location using geolocation.watchPosition and store any changes into the mysql table as they occur so that if the user leaves a defined geofenced area, they receive a notification that they have left the area.
I am able to obtain the users location, update the database with their login and logout locations, and calculate the difference in distance between the two locations. I have the geofences already configured.
How can use geolocation.watchPosition, JS and PHP to update a mysql table each time the user's gps location changes?
The following code sample is what I use to get the user's location and watch their location, but I have not found a way to update the mysql table each time the "info" variable, which contains their location, changes.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
<main class="container">
<div id="map" class="map"></div>
<!-- For displaying user's coordinate or error message. -->
<div id="info" class="info"></div>
</main>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=[KEY]&callback=init"></script>
</body>
</html>
<script type="text/javascript">
const createMap = ({ lat, lng }) => {
return new google.maps.Map(document.getElementById('map'), {
center: { lat, lng },
zoom: 19
});
};
const createMarker = ({ map, position }) => {
return new google.maps.Marker({ map, position });
};
const getCurrentPosition = ({ onSuccess, onError = () => { } }) => {
if ('geolocation' in navigator === false) {
return onError(new Error('Geolocation is not supported by your browser.'));
}
return navigator.geolocation.getCurrentPosition(onSuccess, onError);
};
const getPositionErrorMessage = code => {
switch (code) {
case 1:
return 'Permission denied.';
case 2:
return 'Position unavailable.';
case 3:
return 'Timeout reached.';
default:
return null;
}
}
function init() {
const initialPosition = { lat: 37.658440, lng: -120.993629 };
const map = createMap(initialPosition);
const marker = createMarker({ map, position: initialPosition });
getCurrentPosition({
onSuccess: ({ coords: { latitude: lat, longitude: lng } }) => {
marker.setPosition({ lat, lng });
map.panTo({ lat, lng });
},
onError: err =>
alert(`Error: ${getPositionErrorMessage(err.code) || err.message}`)
});
}
// New function to track user's location.
const trackLocation = ({ onSuccess, onError = () => { } }) => {
if ('geolocation' in navigator === false) {
return navigator.geolocation.watchPosition(onSuccess, onError, {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
});
};
// Use watchPosition instead.
return navigator.geolocation.watchPosition(onSuccess, onError);
};
function init() {
const initialPosition = { lat: 37.658440, lng: -120.993629 };
const map = createMap(initialPosition);
const marker = createMarker({ map, position: initialPosition });
// Use the new trackLocation function.
trackLocation({
onSuccess: ({ coords: { latitude: lat, longitude: lng } }) => {
marker.setPosition({ lat, lng });
map.panTo({ lat, lng });
},
onError: err =>
alert(`Error: ${getPositionErrorMessage(err.code) || err.message}`)
});
}
function init() {
const initialPosition = { lat: 37.658440, lng: -120.993629 };
const map = createMap(initialPosition);
const marker = createMarker({ map, position: initialPosition });
const $info = document.getElementById('info');
trackLocation({
onSuccess: ({ coords: { latitude: lat, longitude: lng } }) => {
marker.setPosition({ lat, lng });
map.panTo({ lat, lng });
// Print out the user's location.
$info.textContent = `Lat: ${lat} Lng: ${lng}`;
// Don't forget to remove any error class name.
$info.classList.remove('error');
},
onError: err => {
// Print out the error message.
$info.textContent = `Error: ${getPositionErrorMessage(err.code) || err.message}`;
// Add error class name.
$info.classList.add('error');
}
});
}
</script>
wacthposition returns an id on each new position.
May be you can try to make a function (callback, promise, interval...) looking for this change. After it occurs, you can insert data into your DB.

how to fix google map center location in vue js

hi create real estate app i have problem in google map if i call location from Json I get error Like this
my html code
name: "Property",
data() {
return {
ref: this.$route.params.ref,
propertydata: {},
center: { lat: 45.508, lng: -73.587 },
markers: [],
places: [],
currentPlace: null
};
},
created() {
this.$http
.get("http://localhost:3000/Listing/" + this.ref)
.then(function(data) {
console.log(data);
this.propertydata = data.body;
this.center=data.body.latitude;
this.center=data.body.longitude;
th
});
<gmap-map :center="{lat: {{propertydata.latitude}} , lng: {{propertydata.longitude}} } " :zoom="14" style="width:500px; height:500px;"></gmap-map>
- invalid expression: Unexpected token { in
{lat: {{propertydata.latitude}} , lng: {{propertydata.longitude}} }
Raw expression: :center="{lat: {{propertydata.latitude}} , lng: {{propertydata.longitude}} } "
my location details from json how to fix this i have no idea
The right way to declare the component is:
<gmap-map :center="{lat: propertydata.latitude, lng: propertydata.longitude}" :zoom="14" style="width:500px; height:500px;"></gmap-map>
You should use {{...}} syntax only inside tags, not in tag attributes.

Angular Google Maps map click event works once

I've been having a problem very similar to this
However that persons question was never answered and my situation is subtly different.
I'm trying to add a click event to my map that will change the center of the map to the location of the click. My code to do this works great, but it only works once and then when I click again I get this error:
angular-google-maps.js:6815 Uncaught TypeError: Cannot read property 'click' of undefined
Here is my map object:
vm.map = {
center: {
latitude: l.latitude,
longitude: l.longitude
},
zoom: 13,
events: {
click: function(map, event, coords) {
vm.map = {
center: {
latitude: coords[0].latLng.lat(),
longitude: coords[0].latLng.lng()
},
};
$scope.apply();
}
}
};
And here's my html:
<ui-gmap-google-map center="location.map.center" zoom="location.map.zoom" draggable="true" options="tabLocations.map.options" events=location.map.events>
<ui-gmap-search-box template="'scripts/components/tab-locations/searchbox.tpl.html'" events="location.map.searchbox.events" parentdiv="'searchbox-container'"></ui-gmap-search-box>
<ui-gmap-marker ng-if="location.active" idKey="1" coords="location" options="{draggable: false, icon: 'images/icons/gps-marker-active.svg'}"></ui-gmap-marker>
<ui-gmap-marker ng-if="!location.active" idKey="1" coords="location" options="{draggable: false, icon: 'images/icons/gps-marker-inactive.svg'}"></ui-gmap-marker>
</ui-gmap-google-map>
After your first click you are redefining a brand new map with no click event:
vm.map = {
center: {
latitude: coords[0].latLng.lat(),
longitude: coords[0].latLng.lng()
},
};
This is overriding all the previous properties you had set before, which includes click.
Use setCenter instead:
click: function(map, event, coords) {
var latLng = new google.maps.LatLng(latitude: coords[0].latLng.lat(), latitude: coords[0].latLng.lng());
vm.map.setCenter(latLng);
}
Reference: Google Maps API

Categories

Resources