i need to display a coordinates field , coming from database, currently am displaying it as an input like this:
i need to display it as map like this:
i googled a LOT and lot of answers on how to load the map using requireJS , but non is working with Magento 2.1..
currently am at this stage:
requirejs.config({
paths: {
googlemaps: 'googlemaps',
async: 'requirejs-plugins/src/async'
},
googlemaps: {
params: {
key: 'xxxxxxxxxxxxxx'
}
}
});
define([
'Magento_Ui/js/form/element/abstract',
'jquery',
'googlemaps!'
],function(Abstract,$,gmaps) {
return Abstract.extend({
initialize: function () {
return this._super();
},
initMap: function() {
console.log(this.value());
console.log("-------------");
var uluru = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
},
});
});
now , question is how to call the initMap function after page is loaded ?
help pleaaaaase
Related
Hi I'm new to stackoverflow (and coding) but I am working on a web-application where I want to add dynamic markers and infowindows based on an extracted JSON file. There are over 200 markers, so they need to be dynamic. I have code that works to add markers but as soon as I add infoWindows it doesn't. Can anybody see why? The output dropped to just one marker and no infoWindow.
Here is my code:
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
infowindow = new google.maps.InfoWindow();
for (element in data) {
new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
infowindow.setContent(data[element].country);
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}
}
});
}
I saw a post on stackoverflow with a similar question and tried it that way as well but didnt get any markers.
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
var json = data = JSON.parse(data);
for (var i = 0; i < json.length; i++) {
point = new google.maps.LatLng(json[i].lat, json[i].lon);
contentString = json[i].Country;
addMarkers(point, contentString);
}
}
});
function addMarkers(point, contentString) {
marker = new google.maps.Marker({
position: point,
map: map
});
infowindow = new google.maps.InfoWindow({
content: contentString
});
marker.push(marker);
infos.push(infowindow);
for (var j = 0; j < markers.length; j++) {
google.maps.event.addListener(markers[j], 'click', function() {
infos[j].open(map, markers[j]);
})
}
}
}
The output of my JSON file looks like this:
{
"AA": {
"celsius": 32.27777777777778,
"country": "AA",
"day": "25",
"lat": 12.5,
"lon": -70.017,
"month": "03"
},
...
}
There are a few issues in your code. You should read Using Closures in Event Listeners.
You should set the infowindow content on marker click (not within the loop, as you did)
You should declare the marker variable which is missing
Any variable you are using must be declared, for example for (element in data) should be for (var element in data)
function initMap() {
var myLatLng = {
lat: 26.967,
lng: -99.25
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
$.ajax({
type: 'GET',
url: 'https://us-central1-cloud-calendar-project.cloudfunctions.net/InfoWindow',
success: function(data) {
data = JSON.parse(data)
console.log(data);
infowindow = new google.maps.InfoWindow();
for (var element in data) {
var marker = new google.maps.Marker({
position: {
lat: data[element].lat,
lng: data[element].lon
},
map: map,
title: element
});
google.maps.event.addListener(marker, 'click', (function(marker, element) {
return function() {
var content = 'Country: ' + data[element].country;
content += '<br>Temperature (°C): ' + data[element].celsius;
infowindow.setContent(content);
infowindow.open(map, marker);
}
})(marker, element));
}
}
});
}
initMap();
#map {
height: 180px;
}
<div id="map"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap" async defer></script>
I have a map with a number of pins on it, the pins are generated from an endpoint api (json). I want to filter the pins via an input that has a v-modal - the search criteria is already set up and is pulled from the same api.
Even if someone can give some tips as to where in the vue lifecycle the filter should happen, i.e mounted, updated computed ect
Originally I used this article as a reference
https://medium.com/#limichelle21/integrating-google-maps-api-for-multiple-locations-a4329517977a
created() {
axios
.get(
`https://cors-anywhere.herokuapp.com/myEndpoint`
)
.then(response => {
// JSON responses are automatically parsed.
this.allProperties = response.data;
this.markers = this.allProperties.map(function (x) {
return {
lat: parseFloat(x.lat).toFixed(3),
lng: parseFloat(x.lng).toFixed(3),
add: x.dispAddress,
propId: x.property_id,
propPrice: x.outputAskingPrice,
propImg: x.imagePath
};
});
this.allProperties = response.data.map(x => {
x.searchIndex = `${x.sellingStatus} ${x.priceType} ${x.typeNames[0]} ${x.typeNames[1]} ${x.dispAddress}`.toLowerCase();
return x;
});
});
},
mounted: function () {
var _this = this;
function initMap() {
var center = {
lat: 53,
lng: -3
};
var map = new google.maps.Map(document.getElementById("map-canvas"), {
zoom: 10,
center: center
});
var newPin = new google.maps.Marker({
position: center,
map: map
});
}
},
updated() {
var _this = this;
var map = new google.maps.Map(document.getElementById("map-canvas"), {
zoom: 9,
center: new window.google.maps.LatLng(55.961, -3)
});
var infowindow = new google.maps.InfoWindow({});
var newPin;
var count;
for (count = 0; count < _this.markers.length; count++) {
newPin = new google.maps.Marker({
position: new google.maps.LatLng(
_this.markers[count].lat,
_this.markers[count].lng
),
map: map,
icon: "../assets/img/map-pin.png"
});
google.maps.event.addListener(
newPin,
"click",
(function (newPin, count) {
return function () {
infowindow.setContent(` ${_this.markers[count].add} <p> ${_this.markers[count].propPrice}</p><img src="${_this.markers[count].propImg}"><p>`);
infowindow.open(map, newPin);
};
})(newPin, count)
);
}
If you have v-model on an <input> field like mentioned in your question, you are binding the value of this <input> field to a variable probably defined in the data part of your Vue component. The value is always up to date in the model (reactive binding). You can watch this value and then trigger a function which updates Google Maps. Here is an example:
Vue.component('demo', {
data () {
return {
inputField: ''
};
},
created () {
console.log('Component script loaded, HTML not yet ready, load the data from your backend. Use a flag like isLoading or similar to indicate when the data is ready to enable input.');
},
mounted () {
console.log('Component mounted, HTML rendered, load Google Maps');
},
watch: {
inputField (newValue) {
console.log(`inputField changed to ${newValue}. Trigger here a method which update Google Maps. Make sure to debounce the input here, so that it does not trigger a Google Maps update too often.`);
}
},
template: `
<div>
<input type="text" v-model="inputField" placeholder="Lookup place">
</div>`
});
new Vue({ el: '#vue-demo-container' });
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="vue-demo-container">
<demo></demo>
</div>
There are two places where i need to show google maps.
I'm using same code for both maps(I mean I'm reusing same code for both maps).
Below are links where you can find screen shots of those two maps.
https://drive.google.com/file/d/0B2JnvvXsAALUdlVzemRVMzNMajF4OFB1V0JXc0RuN1p4eWFV/view - map1
https://drive.google.com/file/d/0B2JnvvXsAALUVGRhNm1HSldhQnpZT3k4S2I2R1YyQkp4OWZz/view - map2
I'm showing second map(map2) in bootstarp modal
first map(map1) is working fine. But in second map(map2), though I have used setCenter method, marker is not showing at center of the map(instead it is showing at top left corner).
what should i do to place marker at center of the map(in second map)?
below is my code..
initialize: function(options){
//initializing the geocoder
this.geocoder = new google.maps.Geocoder();
this.map;
},
//on show of the view
//onShow is a marionette method, which will be triggered when view is shown
onShow: function(){
var address = this.model.get("address");
//render the map with dummy latLang
this.renderMap();
//render the Map with Proper address
if(address!== ""){
this.renderMapWithProperAddress(address);
}
},
renderMap: function(){
var mapCanvas = document.getElementById("mapCanvas"), self = this,
mapOptions = {
center: new google.maps.LatLng(64.855, -147.833),//dummy latLang
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoomControl: false,
mapTypeControl: false,
streetViewControl:false
};
//initializing google map
self.map = new google.maps.Map(mapCanvas, mapOptions);
$("#myModal").on("shown.bs.modal",function(){
google.maps.event.trigger(self.map, "resize");
});
},
renderMapWithProperAddress: function(address){
var self = this,marker;
self.geocoder.geocode( { "address": address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
self.map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: self.map,
position: results[0].geometry.location,
title: address
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
My guess, without seeing your code, is that you need to trigger a map resize event after the bootstrap modal has been shown.
Bootstrap modal
Maps events
$('#myModal').on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
});
Edit:
Here is a complete and working example. As per my comment, you should 1) Trigger a map resize and 2) set the map center to your marker coordinates.
var center = new google.maps.LatLng(59.76522, 18.35002);
function initialize() {
var mapOptions = {
zoom: 7,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: center
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: center
});
}
$('.launch-map').on('click', function () {
$('#modal').modal({
backdrop: 'static',
keyboard: false
}).on('shown.bs.modal', function () {
google.maps.event.trigger(map, 'resize');
map.setCenter(center);
});
});
initialize();
JSFiddle demo
I'm trying to display an embeded Google Map based on the location of an Event object.
This is the basic app:
App = Em.Application.create();
App.Event = Em.Object.extend({
lat: -33.8665433,
lng: 151.1956316
});
App.EventController = Ember.ObjectController.extend();
App.ApplicationController = Ember.ObjectController.extend();
App.EventView = Ember.View.extend({
templateName: 'event'
});
App.ApplicationView = Ember.View.extend({
templateName: 'application'
});
App.Router = Ember.Router.extend({
enableLogging: true,
root: Ember.Route.extend({
event: Ember.Route.extend({
route: '/',
connectOutlets: function (router) {
router.get('eventController').set('content', App.Event.create());
router.get('applicationController').connectOutlet('event');
}
})
})
});
App.initialize();
With the following templates:
<script type="text/x-handlebars" data-template-name="application">
{{outlet}}
</script>
<script type="text/x-handlebars" data-template-name="event">
{{lat}} {{lng}}
// Embeded Google Map
</script>
Where would I initialize the map? Additionally, if lat/lang change, how would I catch it and redraw the map?
Working View Code (Modified from sabithpocker's answer)
App.EventView = Ember.View.extend({
templateName: 'event',
map: null,
latitudeBinding: 'controller.content.lat',
longitudeBinding: 'controller.content.lng',
didInsertElement: function () {
var mapOptions = {
center: new google.maps.LatLng(this.get('latitude'), this.get('longitude')),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(this.$().get(0), mapOptions);
this.set('map', map); //save for future updations
this.$().css({ width: "400px", height: "400px" });
},
reRenderMap: function () {
if (this.get('map')) {
var newLoc = new google.maps.LatLng(this.get('latitude'), this.get('longitude'));
this.get('map').setCenter(newLoc);
}
}.observes('latitude', 'longitude') //these are bound to lat/lng of Event
});
Here is a quick idea, not following ember app structure, just an idea.
App.EventView = Ember.View.extend({
templateName: 'event',
map : null,
latitudeBinding : 'App.Event.lat',
longitudeBinding : 'App.Evet.lng',
didInsertElement : function(){
var mapOptions = {
center: new google.maps.LatLng(this.get('latitude'), this.get('longitude')),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(this.$().get(0),mapOptions);
this.set('map',map); //save for future updations
},
reRenderMap : function(){
var newLoc = new google.maps.LatLng(this.get('latitude'), this.get('longitude'));
this.get('map').setCenter(newLoc)
}.observes('latitude','longitude') //these are bound to lat/lng of Event
});
Also I think App.Event should be:
App.Event = Em.Object.extend({
lat: null,
lng: null,
init : function(){
this.set('lat', -33.8665433);
this.set('lng', 151.1956316);
}
});
to avoid the so-called chromosomal mutation in Ember
i am using gmaps.js (https://github.com/hpneo/gmaps)
I want to add a Marker on the map on clicking a location on the map. If a user clicks on a second location the previous marker should move to the new place or be removed and replaced with a new marker.
Now sure if this is supported by the Lib.
http://bakasura.in/startupsradar/add.html
$(document).ready(function () {
var map = new GMaps({
div: '#map',
lat: 13.00487,
lng: 77.576729,
zoom: 13
});
map.addMarker({
lat: 13.00487,
lng: 77.576729,
title: 'Mink7',
infoWindow: {
content: 'HTML Content'
}
});
/*
GMaps.geolocate({
success: function (position) {
map.setCenter(position.coords.latitude, position.coords.longitude);
},
error: function (error) {
alert('Geolocation failed: ' + error.message);
},
not_supported: function () {
alert("Your browser does not support geolocation");
},
always: function () {
//alert("Done!");
}
});
*/
});
google.maps.event.addListener(_map, "click", function(event) {
if(_marker) {
_marker.setPosition(event.latLng);
} else {
_marker = new google.maps.Marker({
position: event.latLng,
map: _map,
title: "myTitle"
});
}
});
Just saw the other answer, use this if you dont want to create a marker everytime..
_marker should be a global variable.
Personally, I do it using a global variable for the marker (or an array if I need more markers and I want to access them later), so that I can delete it and recreate it somewhere else.
// instantiate your var map
// ...
google.maps.event.addListener(map, "click", function(event) {
if(markermap) {
markermap.setMap(null);
}
markermap = new google.maps.Marker({
position: event.latLng,
map: myMap,
title: "myTitle"
});
});