google maps and browserify - google-maps-api-3

I have my google maps code which is bundled down into a browserify module.
module.exports = function() {
function initMap() {
var myLatLng = {lat: 41.8239898682, lng: -71.4128341675};
var locations = [
['Dorrance Street', 41.8220502,-71.4095081],
['Eddy Street', 41.8249484,-71.4121044],
['Pine Street', 41.8205150,-71.4119489],
// ['Knight Street', 41.8177325,-71.4268190, 4],
['Brown University', 41.8281583,-71.4020998],
];
//more stuff
The problem i am having is the callback is giving the error
Uncaught InvalidValueError: initMap is not a function
Any idea how I can get google maps working with browserify?
Both files are in the the footer and the order does not make a difference.

Related

Map Route Using Average Traffic Conditions

Good morning. I am trying to get my map to show a route based on average traffic conditions on a Monday morning at 11:00am EST. I can do this with the calculateRoute service by appending the following to the service URL:
&depart=".date('Y-m-d', strtotime('monday this week'))."T11:00:00-05
I use this to gather my turn by turn directions, but I would also like the visual route line on the map to reflect this as well. I am very new to JS so please forgive my code, I mainly used the canned demo scripts and modified them to do what I needed. Below is the code for my map. This does also use PHP in the code, but mainly for SQL data and grabbing GET data.
<script>
// Initialize the platform object:
var platform = new H.service.Platform({
'app_id': 'MY APP ID',
'app_code': 'MY APP CODE'
});
// Obtain the default map types from the platform object
var maptypes = platform.createDefaultLayers();
// Obtain the default map types from the platform object:
var defaultLayers = platform.createDefaultLayers();
// Instantiate (and display) a map object:
var map = new H.Map(
document.getElementById('mapContainer'),
defaultLayers.normal.traffic,
{
zoom: 10,
center: { lat: 42.3314, lng: -83.0458 }
}
);
// Create the default UI:
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Enable the event system on the map instance:
var mapEvents = new H.mapevents.MapEvents(map);
// Add event listeners:
map.addEventListener('tap', function(evt) {
// Log 'tap' and 'mouse' events:
console.log(evt.type, evt.currentPointer.type);
});
// Instantiate the default behavior, providing the mapEvents object:
var behavior = new H.mapevents.Behavior(mapEvents);
var routingParameters = {
// The routing mode:
'mode': 'fastest;truck;traffic:enabled',
'waypoint0': 'geo!<?PHP echo $_GET['shipFrom']; ?>',
// The end point of the route:
'waypoint1': 'geo!<?PHP echo $geoCode; ?>',
// To retrieve the shape of the route we choose the route
// representation mode 'display'
'representation': 'display'
};
// Define a callback function to process the routing response:
var onResult = function(result) {
var route,
routeShape,
startPoint,
endPoint,
linestring;
if(result.response.route) {
// Pick the first route from the response:
route = result.response.route[0];
// Pick the route's shape:
routeShape = route.shape;
// Create a linestring to use as a point source for the route line
linestring = new H.geo.LineString();
// Push all the points in the shape into the linestring:
routeShape.forEach(function(point) {
var parts = point.split(',');
linestring.pushLatLngAlt(parts[0], parts[1]);
});
// Retrieve the mapped positions of the requested waypoints:
startPoint = route.waypoint[0].mappedPosition;
endPoint = route.waypoint[1].mappedPosition;
// Create a polyline to display the route
routeLine = new H.map.Polyline(linestring, {
style: { lineWidth: 10 },
arrows: { fillColor: 'white', frequency: 2, width: 0.8, length: 0.7 }
});
// Create a marker for the start point:
var startMarker = new H.map.Marker({
lat: startPoint.latitude,
lng: startPoint.longitude
});
// Create a marker for the end point:
var endMarker = new H.map.Marker({
lat: endPoint.latitude,
lng: endPoint.longitude
});
// Add the route polyline and the two markers to the map:
map.addObjects([routeLine, startMarker, endMarker]);
// Set the map's viewport to make the whole route visible:
map.setViewBounds(routeLine.getBounds());
}
};
// Get an instance of the routing service:
var router = platform.getRoutingService();
// Call calculateRoute() with the routing parameters,
// the callback and an error callback function (called if a
// communication error occurs):
router.calculateRoute(routingParameters, onResult,
function(error) {
alert(error.message);
});
</script>
You could just add the departure parameter in the routingParameters used in the above shared javascript code
var routingParameters = {
// The routing mode:
'mode': 'fastest;truck;traffic:enabled',
'waypoint0': 'geo!<?PHP echo $_GET['shipFrom']; ?>',
// The end point of the route:
'waypoint1': 'geo!<?PHP echo $geoCode; ?>',
// To retrieve the shape of the route we choose the route
// representation mode 'display'
'representation': 'display',
//departure time
'departure' : '2018-10-22T11:00:00-05'
};

Rendering a Google Map without react-google-map

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

Uncaught google.earth not loaded

I'm doing this to add Google Earth to Google Maps v3:
google.load("earth", "1");
// map options
var options = mapster.MAP_OPTIONS,
element = document.getElementById('map-canvas'),
// map
map = mapster.create(element, options);
var ge = new GoogleEarth(map);
The script on my html file looks like this:
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script src="https://www.google.com/jsapi"></script>
<script src="googleearth.js"></script>
<script src="script.js"></script>
I keep getting Uncaught google.earth not loaded and not sure what I did wrong.
I'm using this reference: http://google-maps-utility-library-v3.googlecode.com/svn/trunk/googleearth/docs/reference.html
Here's my full code in case it helps: http://plnkr.co/edit/NlPF3F259IIMgj2pfN09?p=preview
I really want to add Google Earth to Google Maps like the one in here: http://maps.google.com
Is it possible with v3?
Yes - it is possible to integrate the Earth Api with the Maps v3 API - here is a working example.
The problem with your code is the line var ge = new GoogleEarth(map); - you are making this call before the Earth api has finished loading via the asynchronous call to google.load("earth", "1");
This means that google.earth is null when you try and use it and so the Uncaught google.earth not loaded error is thrown.
To fix it you should only call new GoogleEarth(map) once the API has finished loading. The easiest way to do this is probably to use a callback.
For example - you could amend your script.js as follows.
(function(window, google, mapster) {
google.load("earth", "1");
// map options
var options = mapster.MAP_OPTIONS,
element = document.getElementById('map-canvas'),
map = mapster.create(element, options);
// callback method to fire once the api had loaded
google.maps.event.addDomListener(window, 'load', function() { new GoogleEarth(map) });
var marker2 = map.addMarker({
lat: 37.781350,
lng: -122.485883,
draggable: true,
events: [{
name: 'click',
callback: function(e, marker) {
console.log(e, marker);
}
}, {
name: 'dragend',
callback: function() {
alert('dragged');
}
}]
});
// no point calling this here as google.earth will be null
//var ge = new GoogleEarth(map);
}(window, google, window.Mapster));

Google Maps API3 with default Popup & Marker?

Is it possible to show the default Google Maps icon and popup on a custom map?
The default one with the address, title directions nearby etc etc.
This is how i've currently got it set up and working fine apart from the marker..
var map;
jQuery(function($) {
function initialize() {
var styles = [
{
stylers: [
{ "saturation": -100 }
]
}
];
var styledMap = new google.maps.StyledMapType(styles,
{name: "Styled Map"});
var mapOptions = {
zoom: 11,
center: new google.maps.LatLng(55.6468, 37.581),
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
}
};
var map = new google.maps.Map(document.getElementById('map'),
mapOptions);
//Associate the styled map with the MapTypeId and set it to display.
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
}
google.maps.event.addDomListener(window, 'load', initialize);
});
Is it possible to show the default Google Maps icon and popup on a custom map?
The default marker is easy, see the documentation, but the answer for the Google Maps default infowindow is no, but you can create your own infowindow that looks similar and has similar functionality.

Google Places Service giving undefined error

So i recently started to use Maps Api v3 and I am getting and undefined error when I try to make a nearby search. On this line var service_places = new google.maps.places.PlacesService(map);
function setupMap (position) {
// console.log(position);
var curLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// console.log(curLocation);
var mapContainer = document.getElementById('map-container');
var mapOptions = {
zoom: 13,
center: curLocation,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
};
map = new google.maps.Map(mapContainer,mapOptions);
var marker = new google.maps.Marker ({
position: curLocation,
map: map,
title: "I am here :)"
});
getNearMe(curLocation);
}
function getNearMe (curLocation) {
var request = {
loacation: curLocation,
radius: '10000',
types: ['bar', 'night_club']
};
var service_places = new google.maps.places.PlacesService(map);
service_places.nearbySearch(request,function (response,status) {
console.log(status);
console.log(response);
});
}
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<MY-KEY>-fSUI&sensor=false">
</script>
You should include places library in your google api link.
Please try this in index.html:
<script src="http://maps.google.com/maps/api/js?sensor=true&libraries=places" type="text/javascript"></script>
I see a few errors off the bat. For example "location" is misspelled in your request variable.
You also should declare your map variable with "var map". But that's just a style issue. Fix these and see if it works and then we can troubleshoot more.

Resources