Using google map in Vue / Laravel - javascript

Trying to implement google map into Vue component. But having a hard time. Actually, there is no error. But no map also :) Okay, what I tried so far down below.
In laravel blade I set my api.
<script async defer src="https://maps.googleapis.com/maps/api/js?key={{env('GOOGLE_MAPS_API')}}&callback=initMap"></script>
Then in Vue component;
data() {
return {
mapName: "map",
//some other codes
}
},
mounted() {
this.fetchEstates();
},
methods: {
fetchEstates(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
// console.log(response);
this.estates = response.data.data;
//some other codes....
//some other codes....
},
computed: {
//some other functions in computed...
//
initMap: function(){
var options =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), options);
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: this.estates.price,
color: "#fff",
},
position: {
lat: this.estates.lat,
lng: this.estates.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
<div id="map"></div>
and last marker url id bind is in controller like this,
public function details($id)
{
$estates = allestates::where('id', $id)->first();
return view('pages.details', compact('estates'));
}
Do I missing something in Vue js? Thank you!

From our discussion in the comments, I realise that your issue is because this.estates is still not defined when initMap() is executed. Remember that you are using an asynchronous operation (via axios) to populate this.estates, so it is undefined at runtime. What you can do is:
Keep the map initialisation logic in initMap()
Move all the Google Map marker creation until after the axios promise has been resolved. You can abstract all that into another method, e.g. insertMarkers()
Also, remember that you need to define estates in the app/component data, otherwise it will not be reactive.
Here is an example:
data() {
return {
mapName: "map",
// Create the estate object first, otherwise it will not be reactive
estates: {}
}
},
mounted() {
this.fetchEstates();
this.initMap();
},
methods: {
fetchEstates: function(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
this.estates = response.data.data;
// Once estates have been populated, we can insert markers
this.insertMarkers();
//pagination and stuff...
});
},
// Iniitialize map without creating markers
initMap: function(){
var mapOptions =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
},
// Helper method to insert markers
insertMarkers: function() {
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: this.estates.price,
color: "#fff",
},
position: {
lat: this.estates.lat,
lng: this.estates.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
}
},
Update: It also turns out that you have not addressed the issue of the data structure of this.estates. It appears that you are receiving an array from your endpoint instead of objects, so this.estates will return an array, and of course this.estates.lat will be undefined.
If you want to iterate through the entire array, you will have to use this.estates.forEach() to go through each individual estates while adding the marker, i.e.:
data() {
return {
mapName: "map",
// Create the estate object first, otherwise it will not be reactive
estates: {}
}
},
mounted() {
this.fetchEstates();
this.initMap();
},
methods: {
fetchEstates: function(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
this.estates = response.data.data;
// Once estates have been populated, we can insert markers
this.insertMarkers();
//pagination and stuff...
});
},
// Iniitialize map without creating markers
initMap: function(){
var mapOptions =
{
zoom : 6,
center : {
lat:34.652500,
lng:135.506302
}
};
var map = new google.maps.Map(document.getElementById(this.mapName), mapOptions);
},
// Helper method to insert markers
insertMarkers: function() {
// Iterate through each individual estate
// Each estate will create a new marker
this.estates.forEach(estate => {
var marker = new google.maps.Marker({
map: map,
icon: 'imgs/marker.png',
url: "/pages/estates.id",
label: {
text: estate.price,
color: "#fff",
},
position: {
lat: estate.lat,
lng: estate.lng
}
});
google.maps.event.addListener(marker, 'click', function () {
window.location.href = this.url;
});
});
}
},

From what I can see in the screenshot you posted, this.estates is an array of objects? If that's the case you need to iterate through the array using forEach
this.estates.forEach((estate, index) => {
console.log(estate.lat);
//handle each estate object here
});
or use the first item in the array like so this.estates[0].lat, if you're only interested in the first item.

Related

Vue.js cannot show page well

I could see a proper page after refreshing (F5)
I think that there is a problem to render markers
I get a position data to draw markers in map api from Json-server
To get a data, I'm using axios and Async Await function beforeFountain()
When I enter a page, I could not see markers
After refreshing this page (push F5), I could see markers
What I tried to resolve this problem
changed axios get functions, code sequence
Position data:
{
"manholes":[
{
"id":0,
"lat":37.55009275087953,
"lng":127.05067540273716,
"type":"point"
},
{
"id":1,
"lat":37.5501997640179,
"lng":127.04793121391802,
"type":"point"
}
]
}
Vue.js script:
data: () => ({
manholes: [],
}),
beforeMount () {
this.getManholeData()
},
mounted () {
window.kakao && window.kakao.maps
? this.initMap()
: this.addKakaoMapScript()
},
methods: {
// axios get function with async await
async getManholeData () {
try {
const baseURI = 'http://localhost:3000/manholes'
const response = await this.$axios.get(baseURI)
this.manholes = response.data
} catch (ex) {
console.log(ex)
}
},
initMap () {
// Map API config
var container = document.getElementById('map')
var options = {
center: new kakao.maps.LatLng(37.5500792286216, 127.0506923683668),
level: 3,
}
var map = new kakao.maps.Map(container, options)
var imageSrc = require('#/assets/manhole.png')
var imageSize = new kakao.maps.Size(32, 32)
var imageOption = { offset: new kakao.maps.Point(30, 30) }
var markerImage = new kakao.maps.MarkerImage(imageSrc, imageSize, imageOption)
this.manholes.forEach(function (data) {
//use position data
console.log(data.lat)
console.log(data.lng)
var marker = new kakao.maps.Marker({
position: new kakao.maps.LatLng(data.lat, data.lng),
image: markerImage,
map: map,
clickable: true,
})
var iwContent = document.createElement('div')
iwContent.className = 'infowindow'
// iwContent.setAttribute('style', 'width:165px;text-align:center;padding:5px')
}
My problem:
My Goal:

clear and add markers again using marker.remove()

My goal : I want to remove markers from the map and redraw it using setinterval() to update position on the map.
Expected results : remove markers and redraw it again every 4sec.
Actual results : old markers is not removed and new markers are added on it over and over .
Error Massage : there is no Error message to include .
I tried to check if marker is not null and if not null to remove marker from the map (this.marker.remove()) I tried this.marker.removeLayer(this.map) . loop over all markers and remove it one by one or set markers to null .nothing worked . down here i will include the code . i would be happy for any help . thanks in advance .
`` new Vue({
el: '#app',
data: {
/* Data properties will go here */
map: null,
tileLayer: null,
errored: false,
xxx: [],
selectedValue: null,
marker: null,
geocoder: null,
},
computed: {
onlyUnique() {
return [...new Set(this.xxx.map((city => city.location.name)))];
}
},
mounted() {
/* Code to run when app is mounted */ // when the Vue app is booted up, this is run automatically.
this.initMap();
this.getData();
setInterval(this.getData,4000);
},
methods: {
/* Any app-specific functions go here */
initMap() {
this.map = L.map('map', {
center: [20.0, 5.0],
minZoom: 2,
zoom: 2
});
this.tileLayer = L.tileLayer(
'https://cartodb-basemaps-{s}.global.ssl.fastly.net/rastertiles/voyager/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© OpenStreetMap, © CARTO',
subdomains: ['a', 'b', 'c']
}
);
this.tileLayer.addTo(this.map);
},
onChange(event) {
this.selectedValue = event.target.options[event.target.options.selectedIndex].text;
this.geocoder = L.esri.Geocoding.geocodeService();
this.geocoder.geocode().text(this.selectedValue).run((error, response) => {
if (error) {
return;
}
this.map.fitBounds(response.results[0].bounds);
});
},
getData(){
axios
.get('url')
.then(response => {this.xxx= response.data}).catch( error =>{
// handle error
console.log("//////ErroR//////");
console.log(error);
this.errored = true;
});
setTimeout (this.drawMarker,500);
},
drawMarker(){
if (this.marker) {
console.log(this.marker);
this.marker.remove();
}
for (var i = 0; i < this.xxx.length; i++) {
this.marker = new L.marker([this.xxx[i].location.gps.coordinates[1],this.xxx[i].location.gps.coordinates[0]])
.bindPopup("hello")
.addTo(this.map);
}
}
},
});```
Probably a this context scope issue:
setTimeout (this.drawMarker.bind(this), 500)
See also Leaflet- marker click event works fine but methods of the class are undefined in the callback function
This is a classic JavaScript mistake.
this in JavaScript does not necessarily refer to your class instance object. It is the context of the function when it is called.

Google Maps Marker Animation, with KnockoutJs

I'm currently working on a map project with the Google Maps API, and KnockoutJS. I've managed to get most of my framework up and going, but the last piece of functionality is dodging me.
I'm trying to make it so when you click one of the pre-loaded locations on the left navigation bar, that it triggers the Google Maps marker animation, just like clicking on the actual marker does, as well as when filtering the list.
Here's my code so far:
// Define all variables to satisfy strict mode.
var document;
var setTimeout;
var alert;
var ko;
var google;
// Parsing for dynamic background & quote.
function parseQuote(response) {
"use strict";
document.getElementById("quote").innerHTML = response.quoteText;
document.getElementById("author").innerHTML = "Author - <b>" + response.quoteAuthor + "</b>";
}
// Specify all locations on map.
function model() {
"use strict";
var locations = [{
title: "The Hub",
lat: 39.521975,
lng: -119.822078,
id: "The Hub"
}, {
title: "The Jungle",
lat: 39.524982,
lng: -119.815983,
id: "The Jungle"
}, {
title: "Bibo Coffee Company",
lat: 39.536966,
lng: -119.811042,
id: "Bibo Coffee Company"
}, {
title: "Purple Bean",
lat: 39.531135,
lng: -119.833802,
id: "Purple Bean"
}, {
title: "Sips Coffee and Tea",
lat: 39.530438,
lng: -119.814742,
id: "Sips Coffee and Tea"
}];
return locations;
}
var listLocations = ko.observableArray(model());
// Initalize map location & position.
function initMap() {
"use strict";
var map = new google.maps.Map(document.getElementById("map"), {
center: {
lat: 39.529633,
lng: -119.813803
},
zoom: 14
});
// Define markers & content.
listLocations().forEach(function (data) {
var positionMk = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: positionMk,
map: map,
title: data.title,
animation: google.maps.Animation.DROP
});
var infowindow = new google.maps.InfoWindow({
content: data.title
});
data.mapMarker = marker;
marker.addListener("click", function () {
data.triggerMarker(marker);
listLocations().forEach(function (place) {
if (data.title === place.title) {
place.openInfoWindow();
} else {
place.closeInfoWindow();
}
});
});
map.addListener("click", function () {
listLocations().forEach(function (place) {
place.closeInfoWindow();
});
});
var setMk = function (marker) {
infowindow.open(map, marker);
marker.setAnimation(google.maps.Animation.BOUNCE);
setTimeout(function () {
marker.setAnimation(null);
}, 750);
};
data.triggerMarker = setMk.bind();
var openMk = function () {
infowindow.open(map, marker);
};
data.openInfoWindow = openMk.bind();
var closeMk = function () {
infowindow.close(map, marker);
};
data.closeInfoWindow = closeMk.bind();
});
}
// Define ViewModel for list and sorting of list.
function ViewModel() {
"use strict";
var self = {};
self.placeList = ko.observableArray([]);
listLocations().forEach(function (place) {
place.visible = ko.observable(true);
self.placeList.push(place);
});
self.filterValue = ko.observable("");
self.filterList = ko.computed(function () {
listLocations().forEach(function (place) {
var searchParam = self.filterValue().toLowerCase();
var toBeSearched = place.title.toLowerCase();
place.visible(toBeSearched.indexOf(searchParam) > -1);
if (place.mapMarker) {
place.mapMarker.setVisible(toBeSearched.indexOf(searchParam) > -1);
}
if (place.visible() && searchParam && place.mapMarker) {
place.triggerMarker(place.mapMarker);
} else if (place.mapMarker) {
place.closeInfoWindow();
}
});
});
// Responsiveness for clicking locations on the list.
self.onClickListener = function (data) {
listLocations().forEach(function (place) {
if (data.title === place.title) {
place.openInfoWindow();
} else {
place.closeInfoWindow();
}
});
};
return self;
}
ko.applyBindings(new ViewModel());
// Error handling for API's.
function forismaticError() {
"use strict";
alert("Forismatic API is unreachable, please check your internet connection and try again.");
}
function googleMapsError() {
"use strict";
alert("Google Maps API is unreachable, please check your internet connection and try again.");
}
Any insight that can be offered into this would be appreciated! I feel like it's obvious, but my tired brain is failing me.
In addition, here's a quick JSFiddle of the entire project as well.
You just needed to copy the line of code that triggers the animation to your self.onClickListener function:
self.onClickListener = function (data) {
listLocations().forEach(function (place) {
if (data.title === place.title) {
place.openInfoWindow();
place.triggerMarker(place.mapMarker);
} else {
place.closeInfoWindow();
}
});
};

Recreate google map in react

While trying to use google maps in react, dealing with an issue.
First time when the google map component gets created, it works very well.
Problem:- But if I visit some other page and then again go to the same Map containing page, the map is gone. It is not created again.
Here is the component:-
var React = require('react');
var MapLocation = React.createClass({
getInitialState: function() {
return {
map : null
};
},
componentDidMount: function () {
var that = this;
if(document.readyState !== "complete") {
window.addEventListener("load", function () {
that.createMap();
})
}
else {
that.createMap();
}
},
createMap: function () {
var lng = this.props.lng,
lat = this.props.lat,
mapCanvas = this.refs.map_canvas.getDOMNode(),
mapOptions = {
center: new google.maps.LatLng(lng, lat),
zoom: 15,
draggable: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(mapCanvas, mapOptions);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lng, lat),
map: map,
//icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
});
this.setState({map: map});
},
enableScroll: function() {
if(this.state.map) {
this.state.map.set('scrollwheel', true);
this.state.map.set('draggable', true);
}
},
render: function () {
var lat = this.props.lat,
lng = this.props.lng;
return (
<div className='map-location'>
<h3 className='hotel__sub-title'>
Location
</h3>
<div onClick={this.enableScroll} id="google-map" ref='map_canvas'></div>
</div>
)
}
});
module.exports = MapLocation;
According to react documentation:
void componentDidMount()
Invoked once, only on the client (not on the server), immediately after the initial rendering occurs.
It means that after opening other pages and returning to map page again componentDidMount will not be invoked.
I suggest you to use some google maps react modules:
https://github.com/pieterv/react-googlemaps
https://github.com/tomchentw/react-google-maps
Good luck!

Angular-google-maps: How to show Title and Description dynamically on markers

I am using Angular-google-maps, HTML code follows
<ui-gmap-google-map center='mapData.map.center' zoom='mapData.map.zoom'
events="mapEvents">
<ui-gmap-markers models="mapData.map.markers" coords="'self'">
</ui-gmap-markers>
</ui-gmap-google-map>
in JS calling
angular.extend(this, $controller('MapsMixinController',
{$scope:$scope, map:mapData.data[0].map}));
MapsMixinController as follows. Calling this controller from js code. Markers are showing & on click able to mark.
MapsMixinController.js
/**
* Controller providing common behaviour for the other map controllers
*/
angular
.module('app')
.controller('MapsMixinController', ['$scope', 'GeolocationService', 'uiGmapGoogleMapApi', 'map',
function($scope, GeolocationService, GoogleMapApi, map) {
var _this = this;
$scope.mapEvents = {
click: function(mapModel, eventName, originalEventArgs) {
var e = originalEventArgs[0];
if (e.latLng) {
$scope.mapData.map.markers.push({
id: new Date().getTime(),
latitude: e.latLng.lat(),
longitude: e.latLng.lng()
});
// This event is outside angular boundary, hence we need to call $apply here
$scope.$apply();
}
}
};
// Returns a default map based on the position sent as parameter
this.getDefaultMap = function(position) {
return {
markers: [],
center: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
zoom: 14
};
};
// Initialize the google maps api and configure the map
GoogleMapApi.then(function() {
GeolocationService().then(function(position) {
$scope.mapData.map = map || _this.getDefaultMap(position);
}, function() {
$scope.error = "Unable to set map data"; // TODO use translate
});
});
}
]);
How can I show title on mouse hover on markers? And on click how to show description on markers?
You can add title property alone with latitude and longtitude property while creating marker data.
/**
* Controller providing common behaviour for the other map controllers
*/
angular
.module('app')
.controller('MapsMixinController', ['$scope', 'GeolocationService', 'uiGmapGoogleMapApi', 'map',
function($scope, GeolocationService, GoogleMapApi, map) {
var _this = this;
$scope.mapEvents = {
click: function(mapModel, eventName, originalEventArgs) {
var e = originalEventArgs[0];
if (e.latLng) {
$scope.mapData.map.markers.push({
id: new Date().getTime(),
latitude: e.latLng.lat(),
longitude: e.latLng.lng(),
title: "Mouse over text"
});
// This event is outside angular boundary, hence we need to call $apply here
$scope.$apply();
}
}
};
// Returns a default map based on the position sent as parameter
this.getDefaultMap = function(position) {
return {
markers: [],
center: {
latitude: position.coords.latitude,
longitude: position.coords.longitude
},
zoom: 14
};
};
// Initialize the google maps api and configure the map
GoogleMapApi.then(function() {
GeolocationService().then(function(position) {
$scope.mapData.map = map || _this.getDefaultMap(position);
}, function() {
$scope.error = "Unable to set map data"; // TODO use translate
});
});
}
]);

Categories

Resources