I'm trying to upgrade an app into Rails 3. The app requires a map that can be edited and it has been using google maps and mapstraction. When I upgraded to rails 3 the map stopped showing up and I figured that's because it needed to be updated from google maps api v2 to v3.
I've been trying to use this tutorial to upgrade it but because the app is using mapstraction I've been having difficulty getting it to work.
Initially, this was in the html:
<script src="http://maps.google.com/maps?file=api&v=2&key=<%= GOOGLE_MAPS_KEY %>" type="text/javascript"></script>
<script src="/javascripts/mapstraction/mxn.js" type="text/javascript"></script>
<script src="/javascripts/mapstraction/mxn.core.js" type="text/javascript"></script>
<script src="/javascripts/mapstraction/mxn.google.core.js" type="text/javascript"></script>
And the maps.js was as follows:
var Map = function() {
this.init()
}
$.extend(Map.prototype, {
m : false,
init: function() {
this.m = new mxn.Mapstraction('mapdiv', 'googlev3')
this.m.addControls({pan: true, zoom: 'large', map_type: false})
// this.m.enableScrollWheelZoom()
this.m.setMapType(3)
return this.m
},
addPoint: function(lat, lng, html) {
var myPoint = new mxn.LatLonPoint(lat, lng);
var marker = new mxn.Marker(myPoint);
marker.setInfoBubble(html);
this.m.addMarker(marker);
},
setCenterAndZoom: function(center, zoom) {
this.m.setCenterAndZoom(center, zoom)
},
boundingBox: function(lat1, lon1, lat2, lon2) {
var zoom = this.m.getZoomLevelForBoundingBox(new mxn.BoundingBox(lat1, lon1, lat2, lon2))
var centerlng = (lon1 + lon2) / 2
var centerlat = (lat1 + lat2) / 2
var myPoint = new mxn.LatLonPoint(centerlat, centerlng);
this.m.setCenterAndZoom(myPoint, zoom)
},
addPointToLine: function(lat, lng, line, html, length) {
var point = new mxn.LatLonPoint(lat, lng)
line.points.push(point);
var i = line.points.length
var num = 100
if (i == 1) {
m.addPoint(lat, lng, html)
}
},
addUser: function(lat, lng, avatar, html) {
var marker = new mxn.Marker(new mxn.LatLonPoint(lat, lng));
marker.setInfoBubble(html);
marker.setIcon(avatar);
marker.setIconSize([30,30])
m.m.addMarker(marker);
}
});
I tried changing the html to this (based on the upgrade tutorial and the tutorial from mapstraction):
<script src="//maps.googleapis.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script src="http://mapstraction.com/mxn/build/latest/mxn.js?(googlev3)" type="text/javascript"></script>
But when that didn't make a difference I tried to remove mapstraction and change the maps.js to the following:
var Map = function() {
this.init()
}
$.extend(Map.prototype, {
m : false,
init: function() {
this.m = new google.maps.Map(document.getElementById('mapdiv'), {zoom: 13, mapTypeId: google.maps.MapTypeId.HYBRID});
// this.m.addControls({pan: true, zoom: 'large', map_type: false})
// this.m.enableScrollWheelZoom()
// this.m.setMapType(3)
return this.m
},
addPoint: function(lat, lng, html) {
var myPoint = new google.maps.LatLng(lat, lng);
var marker = new google.maps.Marker(myPoint);
marker.setInfoBubble(html);
this.m.addMarker(marker);
},
setCenterAndZoom: function(center, zoom) {
this.m.setCenterAndZoom(center, zoom)
},
boundingBox: function(lat1, lon1, lat2, lon2) {
var zoom = this.m.getZoomLevelForBoundingBox(new google.maps.LatLonAltBox(lat1, lon1, lat2, lon2))
var centerlng = (lon1 + lon2) / 2
var centerlat = (lat1 + lat2) / 2
var myPoint = new google.maps.LatLng(centerlat, centerlng);
this.m.setCenterAndZoom(myPoint, zoom)
},
addPointToLine: function(lat, lng, line, html, length) {
var point = new google.maps.LatLng(lat, lng)
line.points.push(point);
var i = line.points.length
var num = 100
if (i == 1) {
m.addPoint(lat, lng, html)
}
},
addUser: function(lat, lng, avatar, html) {
var marker = new google.maps.Marker(new google.maps.LatLng(lat, lng));
marker.setInfoBubble(html);
marker.setIcon(avatar);
marker.setIconSize([30,30])
m.m.addMarker(marker);
}
});
But still nothing...does anyone have any idea how I can get the map to display?
Thanks
as it seems your code uses jQuery($.extend), did you include jQuery?
all the method you've defined are methods of Map but you try to call these methods for Map.m(which is a google.map.Map-instance and doesn't have such methods)
I don't see where you create the Map-instance(I mean your "class", not the google.maps.Map) at all
a google.maps.Map requires a center-property which is not present(at least not when you create the google.maps.Map-instance in Map.init())
Related
I'm using Google Maps on a ruby on rails site. Code is below:
<div id="map" style='width: 1170px; height: 500px;'></div>
<script>
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map'));
var json = <%=raw #places.to_json %>;
var data;
var service = new google.maps.places.PlacesService(map);
var bounds = new google.maps.LatLngBounds();
if (json.length == 0) {
map.setCenter({lat: 40.736, lng: -73.991});
map.setZoom(11);
}
else {
for (var i = 0, length = json.length; i < length; i++) {
data = json[i].google_key;
if(data != null) {
service.getDetails({placeId: data},function(results, status){
if (status == google.maps.places.PlacesServiceStatus.OK) {
var marker = new google.maps.Marker({
map: map,
place: {
placeId: results.place_id,
location: results.geometry.location
},
});
bounds.extend(results.geometry.location);
map.fitBounds(bounds);
}
});
}
}
}
googleAutocomplete();
}
function googleAutocomplete() {
var input = document.getElementById('place_name');
var autoComplete = new google.maps.places.Autocomplete(input);
autoComplete.addListener('place_changed', function() {
var place = autoComplete.getPlace();
document.getElementById('place_name').value = place.name;
document.getElementById('place_google_key').value = place.place_id;
});
}
</script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA68X13MKpg02y8ZdpKtOUociJqhAg8QyY&libraries=places&callback=initialize" async defer></script>
I get the following error:
You have included the Google Maps API multiple times on this page. This may cause unexpected errors.
I would appreciate any help.
I think your issue is related to turbo-links. Try adding this line to your script tag and see if the error goes away.
data-turbolinks-eval="false"
So your new script tag should look like this:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyA68X13MKpg02y8ZdpKtOUociJqhAg8QyY&libraries=places&callback=initialize" data-turbolinks-eval="false" async defer></script>
Let me know if that helps.
I have a google maps piece of code that gets my current location to a fixed destination but the width and height of the view wont stay the same after i click on the button to get the directions and it looks very unprofessional
The width and height changes once i click on the button. I want the size of the maps to stay the same as before i click the button and once i click the button the size of the maps should remain the same as before and not change
This is the code i have:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<h2>Our Location</h2>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC6v5-2uaq_wusHDktM9ILcqIrlPtnZgEk&sensor=false">
</script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
alert("There is Some Problem on your current browser to get Geo Location!");
}
function success(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var city = position.coords.locality;
var LatLng = new google.maps.LatLng(lat, long);
var mapOptions = {
center: LatLng,
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("MyMapLOC"), mapOptions);
var marker = new google.maps.Marker({
position: LatLng,
title: "<div style = 'height:60px;width:200px'><b>You Are Here:</b><br />Latitude: "
+ lat + +"<br />Longitude: " + long
});
marker.setMap(map);
var getInfoWindow = new google.maps.InfoWindow({ content: "<b>Your Current Location</b><br/> Latitude:" +
lat + "<br /> Longitude:" + long + ""
});
getInfoWindow.open(map, marker);
}
</script>
<script type="text/javascript">
function SearchRoute() {
document.getElementById("MyMapLOC").style.display = 'none';
var markers = new Array();
var myLatLng;
//Find the current location of the user.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(p) {
var myLatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
var m = {};
m.title = "Your Current Location";
m.lat = p.coords.latitude;
m.lng = p.coords.longitude;
markers.push(m);
//Find Destination address location.
var address = document.getElementById("txtDestination").value;
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
m = {};
m.title = address;
m.lat = results[0].geometry.location.lat();
m.lng = results[0].geometry.location.lng();
markers.push(m);
var mapOptions = {
center: myLatLng,
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("MapRoute"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = new Array();
var latlngbounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
var data = markers[i];
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
lat_lng.push(myLatlng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title
});
latlngbounds.extend(marker.position);
(function(marker, data) {
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.title);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array.
var path = new google.maps.MVCArray();
//Getting the Direction Service.
var service = new google.maps.DirectionsService();
//Set the Path Stroke Color.
var poly = new google.maps.Polyline({ map: map, strokeColor: '#4986E7' });
//Loop and Draw Path Route between the Points on MAP.
for (var i = 0; i < lat_lng.length; i++) {
if ((i + 1) < lat_lng.length) {
var src = lat_lng[i];
var des = lat_lng[i + 1];
path.push(src);
poly.setPath(path);
service.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
} else {
alert("Invalid location.");
window.location.href = window.location.href;
}
});
}
}
} else {
alert("Request failed.")
}
});
});
}
else {
alert('Some Problem in getting Geo Location.');
return;
}
}
</script>
</head>
<body>
<form id="SetDirections">
<p>Directions To Elena's Delicacies</p>
<p>
<b>Elena's Delicacies Address:</b>
<input type="text" id="txtDestination" value="499 Paradise Valey Pinetown" style="width: 300px"disabled readonly />
<input type="button" value="Directions" onclick="SearchRoute()" />
</p>
<div id="MyMapLOC" style="width: 100%; height: 600px">
</div>
<div id="MapRoute" style="width: 500px; height: 500px">
</div>
</form>
</body>
</html>
I have an issue with mapbox direction plugin, on a rails app. When I load the page where the map is, I have this error :
Uncaught TypeError: mapboxgl.Directions is not a constructor
at HTMLDocument.<anonymous> (travel.self-10030a4….js?body=1:34)
at fire (jquery.self-bd7ddd3….js?body=1:3233)
at Object.fireWith [as resolveWith] (jquery.self-bd7ddd3….js?body=1:3363)
at Function.ready (jquery.self-bd7ddd3….js?body=1:3583)
at HTMLDocument.completed (jquery.self-bd7ddd3….js?body=1:3618)
Here is the code for my map :
var map;
var directions;
// token access for MAPBOX GL
mapboxgl.accessToken = 'pk.eyJ1IjoiYW50b3RvIiwiYSI6ImNpdm15YmNwNTAwMDUyb3FwbzlzeWluZHcifQ.r44fcNU5pnX3-mYYM495Fw';
// generate map
var map = new mapboxgl.Map({
container: 'map',
style: 'mapbox://styles/mapbox/streets-v10',
center: [-96, 37.8],
zoom: 5
});
// center map on selected marker
map.on('click', 'markers', function (e) {
map.flyTo({center: e.features[0].geometry.coordinates});
});
// change mouse action on enter / leave in marker
map.on('mouseenter', 'markers', function () {
map.getCanvas().style.cursor = 'pointer';
});
map.on('mouseleave', 'markers', function () {
map.getCanvas().style.cursor = '';
});
// Directions
var directions = new mapboxgl.Directions({
unit: 'metric',
profile: 'driving',
container: 'directions'
});
$.ajax({
dataType: 'json',
url: grabTravelData(),
success: function(data) {
geojson = data;
map.addSource("markers", {
"type": "geojson",
"data": {
"type": "FeatureCollection",
"features": data
}
});
map.addLayer({
"id": "markers",
"type": "circle",
"source": "markers",
"paint": {
"circle-radius": 7,
"circle-color": "#ff7e5f"
},
});
// center map on markers
var bounds = new mapboxgl.LngLatBounds();
data.forEach(function(feature) {
bounds.extend(feature.geometry.coordinates);
});
map.fitBounds(bounds);
// test - set direction for each marker to following marker
for(var i = 0; i < data.lenght; i++) {
var last = data.length - 1
var from = data[i];
var to = data[i + 1];
directions.setOrigin(from);
if(to != from) {
directions.setDestination(to);
} else {
directions.setDestination(from);
}
}
}, error: function(data) {
console.log(data + ' error');
}
});
In this code, with a for loop I try to create a routes between each markers with the following marker.
In the header of the app I import mapbox :
<script src='https://api.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.js'></script>
<link href='https://api.mapbox.com/mapbox-gl-js/v0.37.0/mapbox-gl.css' rel='stylesheet' />
<script src="https://cdn.jsdelivr.net/places.js/1/places.min.js"></script>
<script src='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.js'></script>
<link rel='stylesheet' href='https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-directions/v3.1.1/mapbox-gl-directions.css' type='text/css' />
Doest someone know what is this error ?
The proper way to use the Mapbox GL directions is
var directions = new MapboxDirections({
accessToken: 'YOUR-MAPBOX-ACCESS-TOKEN',
unit: 'metric',
profile: 'cycling'
});
map.addControl(directions);
For more details refer the API Documentation
I am new to gmaps4 and i have tried a lot but i was not able to find how to create a geodesic map, if i have single source and multiple destination using gmap4 rails.
So far i have tried this
Js
var locations = [
//Starting Point is "Home", and links to other locations"//
['Home', 37.774930, -122.419416],
['Location-1', 35.689487, 139.691706],
['Location-2', 48.856614, 2.352222],
['Location-3', -33.867487, 151.206990]
]
function initMap() {
var myLatLng = {
lat: 12.363,
lng: -131.044
};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: {
lat: 0,
lng: 0
}
});
var markers = [];
var bounds = new google.maps.LatLngBounds();
// Add the markers and infowindows to the map
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
title: locations[i][0],
map: map
})
markers.push(marker);
bounds.extend(marker.getPosition());
if (i > 0) {
var sitepath = new google.maps.Polyline({
path: [markers[0].getPosition(), marker.getPosition()],
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map
});
}
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
Html
<div id="map"></div>
but i am not able to understand how to do it using gmaps4 rails
im trying to display google maps using html5 geolocation, the code is working fine is jsfiddle but in my mvc application, the map is not being displayed..posting the code below..
this is the link
http://jsfiddle.net/PhzsR/62/
#{
ViewBag.Title = "Home Page";
}
<h2>#ViewBag.Message</h2>
<div id="results"></div>
<div id="map"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var $message_area = jQuery('#results');
jQuery(document).ready(function () {
$message_area.html('<i>Locating you...</i> ');
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function foundLocation(position) {
$message_area.children().remove();
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var accuracy = position.coords.accuracy;
var map;
var centerPosition = new google.maps.LatLng(latitude, longitude);
var options = {
zoom: 12,
center: centerPosition,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map($('#map')[0], options);
var marker = new google.maps.Marker({
position: centerPosition,
map: map,
icon: 'http://google-maps-icons.googlecode.com/files/sailboat-tourism.png'
});
var circle = new google.maps.Circle({
center: centerPosition,
radius: accuracy,
map: map,
fillColor: '#0000FF',
fillOpacity: 0.5,
strokeColor: '#0000FF',
strokeOpacity: 1.0
});
map.fitBounds(circle.getBounds());
$message_area.append('Your latitude: ' + latitude + ' and longitude: ' + longitude + ' and accuracy: ' + accuracy + ':')
}, function (error) {
switch (error.code) {
case error.TIMEOUT:
$message_area.append('Timeout error while finding your location');
break;
case error.POSITION_UNAVAILABLE:
$message_area.append('Position unavailable error while finding your location');
break;
case error.PERMISSION_DENIED:
$message_area.append('Permission denied error while finding your location');
break;
case error.UNKNOWN_ERROR:
$message_area.append('Unknown error while finding your location');
break;
}
});
}
});
</script>
do i need to add any reference for displaying google maps?
If you look at the 'manage resources' tab on your fiddle, you've got a reference to Google Maps API which isn't in your code above, make sure you add
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>