Has anyone been able to render a google map using React and not using the react-google-map plugin? I'm trying something like this:
var MapTab = React.createClass({
render: function() {
return <div className="map-container">
<div id='map' ></div>
</div>
},
componentDidMount: function(){
console.log("Hello")
window.onload = function(){
(function initMap() {
var markers = [];
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 37.7749300, lng: -122.4194200}
});
})();
}
}// end of cdm;
});
module.exports = MapTab;
Nothing I have tried has worked. I have tried capturing the map using refs as well but that did not render the map either. I have placed the google maps script in the header as well (with key) and have verified that the key is valid in a vanilla js project.
With componentDidMount you know you map container div has loaded, but you are not guaranteed that the external maps api has loaded yet. Google provides you the option to give a callback function (initMap() in their examples).
https://maps.googleapis.com/maps/api/js?key=&callback=initMap
Now you can proceed as follows, After your map component did mount you can:
window.initMap = this.initMap to make initMap from react available for Google maps to callback to.
load the google maps JS with initMap parameter.
In this.initMap in your component you can do your map stuff, because now you know your container ánd Google API have loaded.
const React = require('react')
const PropTypes = require('prop-types')
import Reflux from 'reflux'
const Radium = require('radium')
class Map extends Reflux.Component {
constructor(props) {
super(props)
this.loadJS = this.loadJS.bind(this)
this.initMap = this.initMap.bind(this)
}
componentDidMount() {
window.initMap = this.initMap;
if (typeof google === 'object' && typeof google.maps === 'object') {
this.initMap()
} else {
this.loadJS('https://maps.googleapis.com/maps/api/js?key=<API_KEY>&callback=initMap')
}
}
// https://github.com/filamentgroup/loadJS/blob/master/loadJS.js
loadJS(src) {
var ref = window.document.getElementsByTagName("script")[0];
var script = window.document.createElement("script");
script.src = src;
script.async = true;
ref.parentNode.insertBefore(script, ref);
}
initMap() {
var map = new google.maps.Map(this.refs.map, {
center: {lat: -34.397, lng: 150.644},
zoom: 8
})
}
render() {
return (<div ref='map'></div>)
}
}
module.exports = Radium(Map)
get rid of window.onload. By the time componentDidMount method is called window is already loaded so your initMap() function never fires.
It seems that you are not familiar with React Component Life Cycle yet.
https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle
or this: http://busypeoples.github.io/post/react-component-lifecycle/ (this has the table of order in which react's methods are executed)
Actually, in the componentDidMount() ("DID-mount" means the element has already been there on the page, so you can start binding events to it)
React Component's idea is interesting, so we don't need to use javascript's "window.onload()" or jQuery's "$(document).ready()"
Therefore, your code can be revised as follows:
render: function() {
return <div className="map-container">
<div id='map' ></div>
</div>
},
componentDidMount: function(){
console.log("Hello")
var markers = [];
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 37.7749300, lng: -122.4194200}
});
}// end of cdm;
PS: Besides, in order to make the map appear, you need to style the map-container and map correctly (which need a height in pixel, in your case of "0 px width, maybe you need to put the width, too - either in px or 100%) Feel free to style them, though!
You can render a google map easily using React Refs Which are an ideal solution when integrating with third party libraries. Like this:
class App extends React.Component {
constructor(props){
super(props)
this.state = {
// no state for now..
}
// Use createRef() to create a reference to the DOM node we want
this.myMapContainer = React.createRef()
}
componentDidMount() {
// Instead of using: document.getElementById, use the ref we created earlier to access the element
let map = new google.maps.Map(this.myMapContainer.current, {
center: { lat: -34.9973268, lng: -58.582614 },
scrollwheel: false,
zoom: 4
})
}
render() {
return (
<div className="container">
<div ref={this.myMapContainer} id="map"></div>
<div id="text"><p>Google Maps now requires the use of a valid API Key.
That's why you see the popup window "This page can't load Google Maps correctly."</p>
Go get one!
</div>
</div>
)
}
}
Working Example here
Note: Don't forget to place the <script> that makes the call to the Google Maps API. If you created your project using create-react-app, you can place the script inside of public/index.html
Related
I have several modal buttons which on click should show pre-saved Map Route in PolyLine.
Below code I used on php Ajax Modal Call. $jsline, $center_lat, $center_lng are php variable which are determined on modal click by ajax query.
<div id="map" style="width:100%;height:450px"></div>
<script>
$(document).on("shown.bs.modal", function () {
function addPolylineToMap(map) {
var lineString = new H.geo.LineString();
'.$jsline.'
map.addObject(new H.map.Polyline(
lineString, { style: { lineWidth: 4 }}
));
}
var platform = new H.service.Platform({
apikey: myhereapi
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(document.getElementById("map"),
defaultLayers.vector.normal.map,{
center: {lat:'.$center_lat.', lng:'.$center_lng.'},
zoom: 5.65,
pixelRatio: window.devicePixelRatio || 1
});
window.addEventListener("resize", () => map.getViewPort().resize());
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var ui = H.ui.UI.createDefault(map, defaultLayers);
addPolylineToMap(map);
});
</script>
If I remove on("shown.bs.modal") modal window pops up with blank map (white background, no map). When I use on("shown.bs.modal") modal window pops up and work properly on first click. However, second, third, and further clicks will stack maps. I mean in second click there 2 maps appear. In third click 3 maps appear.
Why maps get stacked ? How to resolve this issue ? As far as I can see no one else faced with similar problem before.
I managed to find solution, so I am sharing it if anyone else faces with such issue.
I have added $("#map").empty(); just before new instance of map is loaded as below.
<div id="map" style="width:100%;height:450px"></div>
<script>
$(document).on("shown.bs.modal", function () {
function addPolylineToMap(map) {
var lineString = new H.geo.LineString();
'.$jsline.'
map.addObject(new H.map.Polyline(
lineString, { style: { lineWidth: 4 }}
));
}
$("#map").empty();
var platform = new H.service.Platform({
apikey: myhereapi
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(document.getElementById("map"),
defaultLayers.vector.normal.map,{
center: {lat:'.$center_lat.', lng:'.$center_lng.'},
zoom: 5.65,
pixelRatio: window.devicePixelRatio || 1
});
window.addEventListener("resize", () => map.getViewPort().resize());
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var ui = H.ui.UI.createDefault(map, defaultLayers);
addPolylineToMap(map);
});
</script>
I am trying to create a extension in Firefox using sdk addon. What i want to do is to call an iframe inside a panel.
I have already created the extension for chrome and now i am trying to do it for firefox.
I have a facebook login in the iframe. Once i click on the sign in button the iframe just goes blank. If I log in before hand then also the extension doesnt work. It is as if it can't access the session.
Here is the code of my main.js file.
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var data = require("sdk/self").data;
var {Cc, Ci} = require("chrome");
var tabs = require("sdk/tabs");
var title=tabs.activeTab.title;
var button = ToggleButton({
id: "my-button",
label: "my button",
icon: {
"16": "./logo1.png",
"32": "./logo1.png",
"64": "./logo1.png"
},
onChange: handleChange
});
var panel = panels.Panel({
width:450,
height:400,
contentURL: data.url("popup.html"),
onHide: handleHide
});
function handleChange(state) {
if (state.checked) {
panel.show({
position: button
});
}
}
function handleHide() {
button.state('window', {checked: false});
}
here is the code of my main javascript file that calls the iframe
$(document).ready(function() {
document.body.style.display = 'block';
var ur='xyz';
var frame = document.createElement('iframe');
var frame_url = 'https://developer.mozilla.org/en-US/Add-ons/SDK/High-Level_APIs/page-mod';
frame.setAttribute('width', '100%');
frame.setAttribute('height', '100%');
// frame.setAttribute('margin', '-10%');
frame.setAttribute('frameborder', 'none');
frame.setAttribute('id', 'rtmframe');
$('body').height(450).width(400);
frame.setAttribute('src', frame_url);
document.body.appendChild(frame);
$('iframe#rtmframe').load(function() {
$('#loadImg').hide();
});
});
This is not the actual link i am trying to open. Can anyone suggest what i can do differently. or point me to github code that might be doing the same thing.
I known this question has been raised and answered many times but I can't seem to make the suggested solutions work for me...
I'm displaying a google map within a simplemodal dialogue.
Outside the modal dialogue the map displays correctly.
However, once inside a modal wrapper only part of the map is shown on the first iteration (see below).
The solution would appear to involve binding a 'resize' event to the map but it isn't working for me...
First iteration:
On opening the modal for the first iteration, my map displays with the partial section displaced over to the top RHS and overlaid on the full map.
On closing the first dialogue the screen returns to it's initial state.
Second and subsequent iterations:
On subsequent iterations the map displays correctly but on closing the background color of the map canvas is visible.
HTML:
<body>
<button class="modalMap">With Modal </button>
<button class="nonModalMap">Without Modal </button>
<div id="mapCanvas"></div>
</body>
CSS:
#simplemodal-overlay {background-color:#000;}
#simplemodal-container {color:#999; background-color:#fff;}
#simplemodal-container a{color:#ddd;}
.modalMap:hover,.nonModalMap:hover {
cursor:pointer;
}
#mapCanvas {
position:relative;
width:480px;height:300px;
}
JS:
$(document).ready(function(){
var myMap;
$('.modalMap').click(function(){
buildMap();
$('#mapCanvas').modal(
{onOpen:function(dialog){
dialog.overlay.fadeIn('fast',function(){
dialog.data.hide();dialog.container.fadeIn('fast',function(){
dialog.data.slideDown('fast');
});
});
}
,onClose:function(dialog){
dialog.data.fadeOut('fast',function(){
dialog.container.hide('fast',function(){
dialog.overlay.slideUp('fast',function(){
$.modal.close();
});
});
});
}
});
});
/* But without the modal the map displays correctly... */
$('.nonModalMap').click(function(){
buildMap();
});
});
function buildMap() {
var kpl = {
Place: function (data, map) {
var self = this;
this.data = data;
var coords = data.geo_coords.split(',');
this.position = new google.maps.LatLng(coords[0], coords[1]);
this.marker = new google.maps.Marker({
position: this.position,
map: map
});
google.maps.event.addListener(this.marker, 'click', function() {
if (self.data.url) {
window.location.href = self.data.url
}
});
},
MapManager: function (div, data) {
this.map = new google.maps.Map(div, {
zoom: 15,
center: new google.maps.LatLng(53.818298, -1.573263),
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
backgroundColor: '#cccccc',
streetViewControl: false,
navigationControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
});
saveCenter = this.map.center;
this.places = [];
for (var i in data) {
if (data.hasOwnProperty(i)) {
this.places.push(new kpl.Place(data[i], this.map));
}
}
}
};
myMap = new kpl.MapManager($('#mapCanvas').get(0), [{
url: "mailto:info#????.com",
geo_coords: "53.818298, -1.573263",
name: "Kensington Property LS6"
}]);
}
/* plus the simplemodal library... */
I've recreated the code in jsfiddle - http://jsfiddle.net/redApples/j23ue0n1/32/
Can anybody rescue my sanity...?
I am using google places autocomplete api and now I want to get the geocode of that address and display that area on map.This is my code...
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initialize() {
var input = document.getElementById('searchTextField');
var autocomplete = new google.maps.places.Autocomplete(input);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input id="searchTextField" type="text" size="50">
</body>
I know there is google geocde api but I really dont know how to do that.
I m doing all this in wordpress. Anybody has idea about this???
Looks like that's what you need:
<style>
#map-canvas {
width: 500px;
height: 500px;
}
</style>
Then, the JS
function initialize() {
// initial zoom and position
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(-25.3, 133.8)
};
// create Map instance
var map = new google.maps.Map(document.getElementById('map-canvas'), myOptions);
// get input reference
var input = document.getElementById('searchTextField');
// create instance of autocomplete
var autocomplete = new google.maps.places.Autocomplete(input);
// listen for changes
google.maps.event.addListener(autocomplete, 'place_changed', function() {
// get the selected place
var place = this.getPlace();
// if there's a geometry available
if (place.geometry) {
// move the map to the position
map.panTo(place.geometry.location);
// update the zoom
map.setZoom(15);
// log the position
console.log(place.geometry.location.lat(),place.geometry.location.lng() )
}
})
}
More info: https://developers.google.com/maps/documentation/javascript/places-autocomplete
Now that I have found a way to initialize Google Maps with the help of Andy Joslin in this SO initialize-google-map-in-angularjs, I am looking for a way to asynchronous load a Google Map Object.
I found an example of how to do this in the phonecat project.
Notice how the JS files are loaded in this example: index-async.html
In my Jade Scripts partial that is loaded into my program I tried:
script(src='js/lib/angular/angular.js')
script(src='js/lib/script/script.min.js')
script
$script([
'js/lib/angular/angular-resource.min.js',
'js/lib/jquery/jquery-1.7.2.min.js',
'http://maps.googleapis.com/maps/api/js?key=AIzaSyBTmi_pcXMZtLX5MWFRQgbVEYx-h-pDXO4&sensor=false',
'js/app.js',
'js/services.js',
'js/controllers.js',
'js/filters.js',
'js/directives.js',
'bootstrap/js/bootstrap.min.js'
], function() {
// when all is done, execute bootstrap angular application
angular.bootstrap(document, ['ofm']);
});
When I do this and go to load the map page I get:
A call to document.write() from an asycrononously-loaded
external script was ignored.
This is how Google Maps is being loaded now as a service:
'use strict';
var app = angular.module('ofm.services', []);
app.factory('GoogleMaps', function() {
var map_id = '#map';
var lat = 46.87916;
var lng = -3.32910;
var zoom = 15;
var map = initialize(map_id, lat, lng, zoom);
return map;
});
function initialize(map_id, lat, lng, zoom) {
var myOptions = {
zoom : 8,
center : new google.maps.LatLng(lat, lng),
mapTypeId : google.maps.MapTypeId.ROADMAP
};
return new google.maps.Map($(map_id)[0], myOptions);
}
It appears that this should be returning a promise from what I recall reading. But this AngularJS is very new to me.
here's my solution I came up without using jQuery:
(Gist here)
angular.module('testApp', []).
directive('lazyLoad', ['$window', '$q', function ($window, $q) {
function load_script() {
var s = document.createElement('script'); // use global document since Angular's $document is weak
s.src = 'https://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize';
document.body.appendChild(s);
}
function lazyLoadApi(key) {
var deferred = $q.defer();
$window.initialize = function () {
deferred.resolve();
};
// thanks to Emil Stenström: http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
if ($window.attachEvent) {
$window.attachEvent('onload', load_script);
} else {
$window.addEventListener('load', load_script, false);
}
return deferred.promise;
}
return {
restrict: 'E',
link: function (scope, element, attrs) { // function content is optional
// in this example, it shows how and when the promises are resolved
if ($window.google && $window.google.maps) {
console.log('gmaps already loaded');
} else {
lazyLoadApi().then(function () {
console.log('promise resolved');
if ($window.google && $window.google.maps) {
console.log('gmaps loaded');
} else {
console.log('gmaps not loaded');
}
}, function () {
console.log('promise rejected');
});
}
}
};
}]);
If you using jQuery in your AngularJS app, check out this function which returns a promise for when the Google Maps API has been loaded:
https://gist.github.com/gbakernet/828536
I was able to use this in a AngularJS directive to lazy-load Google Maps on demand.
Works a treat:
angular.module('mapModule') // usage: data-google-map
.directive('googleMap', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
// If Google maps is already present then just initialise my map
if ($window.google && $window.google.maps) {
initGoogleMaps();
} else {
loadGoogleMapsAsync();
}
function loadGoogleMapsAsync() {
// loadGoogleMaps() == jQuery function from https://gist.github.com/gbakernet/828536
$.when(loadGoogleMaps())
// When Google maps is loaded, add InfoBox - this is optional
.then(function () {
$.ajax({ url: "/resources/js/infobox.min.js", dataType: "script", async: false });
})
.done(function () {
initGoogleMaps();
});
};
function initGoogleMaps() {
// Load your Google map stuff here
// Remember to wrap scope variables inside `scope.$apply(function(){...});`
}
}
};
}]);
Take a look of this i think its more reliable
var deferred = $q.defer();
var script = document.createElement('script');
$window.initMap = function() {
//console.log("Map init ");
deferred.resolve();
}
script.src = "//maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places&callback=initMap";
document.body.appendChild(script);
return deferred.promise;