markerwithlabel didnt display on google map on meteorjs - javascript

markerwithlabel didnt display on google map on meteorjs. I am using dburles:google-maps and markerwithlabel v1.1.9. I cant seem to be able to integrate with dburles:google-maps and i placed markerwithlabel.js in public folder
I have this error
Uncaught TypeError: google.maps.MarkerWithLabel is not a function
GoogleMap.jsx
Map = React.createClass({
propTypes: {
name: React.PropTypes.string.isRequired,
options: React.PropTypes.object.isRequired
},
componentDidMount() {
GoogleMaps.create({
name: this.props.name,
element: React.findDOMNode(this),
options: this.props.options
})
GoogleMaps.ready(this.props.name, function(map) {
var marker = new google.maps.MarkerWithLabel({ <-----------ERROR
position: map.options.center,
map: map.instance,
zoom: 8
})
})
},
componentWillUnmount() {
if (GoogleMaps.maps[this.props.name]) {
google.maps.event.clearInstanceListeners(GoogleMaps.maps[this.props.name].instance);
delete GoogleMaps.maps[this.props.name];
}
},
render() {
return <div className="map-container"></div>;
}
})
Home.jsx
Home = React.createClass({
mixins: [ReactMeteorData],
componentDidMount() {
GoogleMaps.load({key: "AIzaSyAIoRRWbFOLmP4iLXrRmgDmNw0STlKMXqU"})
},
getMeteorData() {
return {
loaded: GoogleMaps.loaded(),
mapOptions: GoogleMaps.loaded() && this._mapOptions()
}
},
_mapOptions() {
return {
center: new google.maps.LatLng(1.3, 103.8),
zoom: 8
}
},
render() {
if (!this.data.loaded) {
return <div>Loading map...</div>
}
const script = document.createElement('script')
script.type = 'text/javascript'
script.src = '/markerwithlabel.js'
document.body.appendChild(script)
return <Map name="mymap" options={this.data.mapOptions}/>
}
})

Finally i get it. its a little dumb just use MarkerWithLabel rather than google.map.MarkerWithLabel because the api doesnt comes from google maps api
GoogleMaps.ready(this.props.name, function(map) {
var marker = new MarkerWithLabel({
position: map.options.center,
map: map.instance,
zoom: 8,
labelContent: "$425K",
})
})

Related

Map component occasionally throws an error: Uncaught (in promise), "H.map.DataModel#add (Argument #0 [object Object])"

I'm using Here Maps (Freemium plan) in a VueJs application that uses vue-router.
I made a Vue component for displaying a map which uses Routing to create an SVG path between 2 points following this articles:
https://developer.here.com/blog/showing-a-here-map-with-the-vue.js-javascript-framework
https://developer.here.com/documentation/map-image/dev_guide/topics/examples-routing-new-york-pois.html
I include Here Maps library ver 3.1 (CDN):
https://js.api.here.com/v3/3.1/mapsjs-service.js
https://js.api.here.com/v3/3.1/mapsjs-data.js
https://js.api.here.com/v3/3.1/mapsjs-ui.js
https://js.api.here.com/v3/3.1/mapsjs-mapevents.js
But the Vue component occasionally throws an error:
Uncaught (in promise) D {message: "H.map.DataModel#add (Argument #0 [object Object])"
The things I've noticed are:
If I reload the page sometimes it works fine and sometimes not
With certain route paths it works everytime
I've tried so hard to find the problem, no luck.
I think maybe it's the combination of vue-router and loading Here Maps library through CDN that causes this problem.
Is there a npm package for Here Maps out there?
Have you also experienced this issue?
Here is the code my map Vue component.
<template>
<div>
<div ref="map" class="here-map__map" />
</div>
</template>
<script>
export default {
data() {
return {
map: {},
coordinates: { lat: 46, lng: 12 },
platform: {},
waypoints: [],
markers: [],
icon: ''
}
},
props: {
property: {
zoom: 8,
markerIcon: "marker",
routing: {
route": {
color: "#ff815b",
width: 3
},
mode: {
type: "fastest",
transport: "truck",
traffic: "traffic:disabled"
}
}
},
appId: YOUR_APP_ID,
appCode: YOUR_APP_CODE
},
computed: {
route() {
return this.property.routing.route
},
routingParameters() {
return {
mode:
this.property.routing && this.property.routing.mode
? Object.values(this.property.routing.mode).join(';')
: ''
}
}
},
async created() {
await this.initMap()
},
beforeDestroy() {
this.map = null
},
methods: {
async initMap() {
this.platform = await new H.service.Platform({
apikey: YOUR_API_KEY
})
await this.getCoordinates()
this.createMap()
},
getCoordinates() {
if (this.property.lat && this.property.lng) {
this.coordinates = { lat: this.property.lat, lng: this.property.lng }
} else {
this.getGeoCoordinates()
}
},
getGeoCoordinates() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(pos => {
this.coordinates = {
lat: pos.coords.latitude,
lng: pos.coords.longitude
}
})
} else {
console.warn('This browser does not support geolocalization.')
}
},
calculateWaypoints() {
if (this.property.routing && this.property.routing.waypoints) {
this.waypoints = this.property.routing.waypoints.map((item, index) => {
this.routingParameters[`waypoint${index}`] = `geo!${item.lat},${
item.lng
}`
})
} else {
this.routingParameters.waypoint0 = this.shipment
? `geo!${this.shipment.from_address.lat},${
this.shipment.from_address.lng
}`
: null
this.routingParameters.waypoint1 = this.shipment
? `geo!${this.shipment.to_address.lat},${
this.shipment.to_address.lng
}`
: null
}
},
calculateRoute() {
this.platform.getRoutingService().calculateRoute(
this.routingParameters,
result => {
if (result.response.route) {
let route = result.response.route[0]
let lineString = new H.geo.LineString()
route.shape.forEach(function(point) {
let parts = point.split(',')
lineString.pushLatLngAlt(parts[0], parts[1])
})
let routeLine = lineString
? new H.map.Polyline(lineString, {
style: {
strokeColor: this.route.color || '#000000',
lineWidth: this.route.width || 2
}
})
: null
this.drawWaypoints(route)
let mapObjects = [...this.markers, routeLine]
this.map.addObjects(mapObjects)
this.map.getViewModel().setLookAtData({
bounds: routeLine.getBoundingBox()
})
}
},
error => {
console.log(error)
}
)
},
drawWaypoints(route) {
route.waypoint.map(({ mappedPosition }, index) => {
this.markers.push(
new H.map.Marker(
{
lat: mappedPosition.latitude,
lng: mappedPosition.longitude
},
{ icon: this.icon }
)
)
})
},
async createMap() {
this.icon = new H.map.Icon(`/${this.property.markerIcon}.svg`)
let defaultLayers = await this.platform.createDefaultLayers()
this.map = new H.Map(
this.$refs[this.ref],
defaultLayers.vector.normal.map,
{
zoom: this.property.zoom,
center: this.coordinates
}
)
let events = new H.mapevents.MapEvents(this.map)
let behavior = new H.mapevents.Behavior(events)
let ui = H.ui.UI.createDefault(this.map, defaultLayers)
this.calculateWaypoints()
this.calculateRoute()
window.addEventListener('resize', () => {
this.map.getViewPort().resize()
})
}
}
}
</script>
<style lang="scss">
.here-map {
&__map {
height: 400px;
margin: 0 auto;
}
}
</style>
Thank you in advance.
Yes, we have a blog how to implement HERE JS API into VueJs but basically we don't realize а technically support an integration of third part libraries/frameworks with HERE JS API.
But any way some recommendations:
Please include all HERE JS libraries (mapsjs-core.js, mapsjs-service.js etc.) into the <head> HTML element like in our examples https://developer.here.com/documentation/examples/maps-js
Please keep the description how to initialize the map in our blog https://developer.here.com/blog/showing-a-here-map-with-the-vue.js-javascript-framework. There is "Because the map is a DOM component, we need to wait until the components have rendered before we try to work with it, so we can’t do it in the created method. Instead we can use the mounted method". But in your code you use created method.
Keep in mind that HERE map container element should not be part of Virtual DOM of Vue

OverlappingMarkerSpiderfier is not defined (Vue.js)

I'm trying to implement the OverlappingMarkerSpiderfier for my Google Maps, and it works because my markers are able to "spiderfy" when I click on a marker.
My issue is that in my dev console on VS Code, ESLint is still giving me the error 'OverlappingMarkerSpiderfier' is not defined. I don't really know what the issue is since my markers are working as intended when I click on them. Below is a picture showing that OverlappingMarkerWorkers even though there is an error from ESLint:
I want to get rid of the error in case a future error arises because of it. I've searched for solutions, and many people have commented that OverlappingMarkerSpiderfier should be loaded after Google Maps load. I've done that, but the error still persists.
I load my Google Maps asynchronously; below is my .js file that loads the Google Maps and OverlappingMarkerSpiderfier:
import api_keys from './api_keys'
const API_KEY = api_keys.google_maps_api_key;
const CALLBACK_NAME = 'gmapsCallback';
let initialized = !!window.google;
let resolveInitPromise;
let rejectInitPromise;
const initPromise = new Promise((resolve, reject) => {
resolveInitPromise = resolve;
rejectInitPromise = reject;
});
export default function init() {
if (initialized) return initPromise;
initialized = true;
window[CALLBACK_NAME] = () => resolveInitPromise(window.google);
const script = document.createElement('script');
script.async = true;
script.defer = true;
script.src = `https://maps.googleapis.com/maps/api/jskey=${API_KEY}&callback=${CALLBACK_NAME}`;
script.onerror = rejectInitPromise;
document.querySelector('head').appendChild(script);
const spiderfier = document.createElement('script');
spiderfier.defer = true;
spiderfier.src = "https://cdnjs.cloudflare.com/ajax/libs/OverlappingMarkerSpiderfier/1.0.3/oms.min.js";
spiderfier.onerror = rejectInitPromise;
document.querySelector('head').appendChild(spiderfier);
return initPromise;
}
The following is my GoogleMaps component. The OverlappingMarkerSpiderfier implementation is located within "watch":
<template>
<div id="google-map">
</div>
</template>
<script>
import gMaps from '../lib/gMaps.js'
export default {
name: 'GoogleMaps',
props: {
events: Array
},
data() {
return {
map: null,
locations: []
}
},
async mounted() {
try {
const google = await gMaps();
const geocoder = new google.maps.Geocoder();
this.map = new google.maps.Map(this.$el);
geocoder.geocode({ address: 'USA'}, (results, status) => {
if (status !== 'OK' || !results[0]) {
throw new Error(status);
}
this.map.setCenter(results[0].geometry.location);
this.map.fitBounds(results[0].geometry.viewport);
});
} catch (error) {
console.error(error);
}
},
watch: {
async events() { //creates markers for the map; data is from a 3rd party API that is handled by a different component
try {
const google = await gMaps();
var oms = new OverlappingMarkerSpiderfier(this.map, {
markersWontMove: true,
markersWontHide: true,
basicFormatEvents: true
})
for(let i = 0; i < this.events.length; i++) {
let marker = new google.maps.Marker({
position: {
lat: parseInt(this.events[i].latitude, 10),
lng: parseInt(this.events[i].longitude, 10)
},
map: this.map,
title: this.events[i].title
})
let iw = new google.maps.InfoWindow({
content: this.events[i].description || 'No description available.'
});
google.maps.event.addListener(marker, 'spider_click', function() {
iw.open(this.map, marker);
});
oms.addMarker(marker);
}
}
catch(error) {
console.error(error)
}
}
}
}
</script>
<style lang="scss" scoped>
#google-map {
width: auto;
height: 100vh;
}
</style>
try either 1 of these
this.$nexttick(()=>{
code in mounted hook....
})
check if window.google object is loaded and your map reference is available before instantiating OverlappingMarkerSpiderfier.

Using google map in Vue / Laravel

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.

add marker to the google maps in angular component

I am trying to add marker to the google maps.
but I am facing below error.
InvalidValueError: setMap: not an instance of Map; and not an instance of StreetViewPanorama
can you tell me how to fix it.
providing code and stackblitz below.
https://stackblitz.com/edit/angular-gmaps-api-suvdaf?file=src/app/map-loader.ts
return MapLoader.load().then((gapi) => {
this.map = new google.maps.Map(gmapElement.nativeElement, {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: type,
// label: "A"
});
this.map1 = new google.maps.Marker({
label: "A",
position: { lat: 59.33555, lng: 18.029851 },
map: map,
title: 'Hello World!'
});
// let markerSimple = new google.maps.Marker({
// label: "A",
// position: { lat: 59.33555, lng: 18.029851 },
// map: map,
// title: 'Hello World!'
// });
});
If i have understand your question this modified code will add markers
import { Injectable } from '#angular/core';
import { } from '#types/googlemaps';
declare var window: any;
// Credits to: Günter Zöchbauer
// StackOverflow Post: https://stackoverflow.com/a/39331160/9687729
#Injectable()
export class MapLoader {
private static promise;
map: google.maps.Map;
public static load() {
if (!MapLoader.promise) { // load once
MapLoader.promise = new Promise((resolve) => {
window['__onGapiLoaded'] = (ev) => {
console.log('gapi loaded')
resolve(window.gapi);
}
console.log('loading..')
const node = document.createElement('script');
node.src = 'https://maps.googleapis.com/maps/api/js?callback=__onGapiLoaded';
node.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(node);
});
}
return MapLoader.promise;
}
initMap(gmapElement, lat, lng, zoom, type) {
return MapLoader.load().then((gapi) => {
this.map = new google.maps.Map(gmapElement.nativeElement, {
center: new google.maps.LatLng(lat, lng),
zoom: zoom,
mapTypeId: type,
// label: "A"
});
//after map load add markers
this.createMarker();
});
}
createMarker() {
// list of hardcoded positions markers
var myLatLngList = {
myLatLng : [{ lat: 37.76487, lng: -122.41948 }, { lat: 59.33555, lng: 18.029851 }]
};
//iterate latLng and add markers
for(const data of myLatLngList.myLatLng){
var marker = new google.maps.Marker({
position: data,
map: this.map,
title: 'markers'
});
}
};
}

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!

Categories

Resources