google maps v3 setCenter for map - javascript

I am not sure where to add the setCenter as my map is currently centering to the LatLng above where i put my var setCenter code below, my javascript is terrible so I don't even know really what is going on below, i just copy pasted the code down there, so for me to look at other examples on stackexchange will not work, if anyone knows where i would put the setCenter would be much appreciated.
var directionDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
var latlng = new google.maps.LatLng(-33.8333406,18.6470022);
var setCenter = new google.maps.LatLng(37.4419, -122.1419);
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
var map = new google.maps.Map(document.getElementById("map"),myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directionsPanel"));
var marker = new google.maps.Marker({
position: latlng,
map: map,
title:"Get Directions"
});
}
function calcRoute() {
var start = document.getElementById("routeStart").value;
var end = "-33.8333406,18.6470022";
var request = {
origin:start,
destination:end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
if (status == 'ZERO_RESULTS') {
alert('No route could be found between the origin and destination.');
} else if (status == 'UNKNOWN_ERROR') {
alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
} else if (status == 'REQUEST_DENIED') {
alert('This webpage is not allowed to use the directions service.');
} else if (status == 'OVER_QUERY_LIMIT') {
alert('The webpage has gone over the requests limit in too short a period of time.');
} else if (status == 'NOT_FOUND') {
alert('At least one of the origin, destination, or waypoints could not be geocoded.');
} else if (status == 'INVALID_REQUEST') {
alert('The DirectionsRequest provided was invalid.');
} else {
alert("There was an unknown error in your request. Requeststatus: \n\n"+status);
}
}
});
}

This line:
var latlng = new google.maps.LatLng(-33.8333406,18.6470022);
gives you a latlng object, which you later used in map options, to center the map.
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};
If you want to use setCenter latlng object to be used as center of map, then change it in map options.
var setCenter = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 8,
center: setCenter, // setCenter latlng, defined above will be used to center tha map
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false
};

Related

Google maps API DirectionsService between lat and long and GeolocationMarker

I am trying to get the directions services working on google maps api v3.
It is a webapp for smartphones where the user can get directions from where they are (GeolocationMarker) to a static (hardcoded) location defined by a lat and long.
The map centres on the hard coded lat and long, and then I have an icon (gps.png) that onclick should calculate and plot the directions between the two points.
I am not overly strong in javascript and this is essentially a mashup of code...can anyone see what I have done wrong and why this wont work?
Javascript is:
<code>
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var arena = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var mapOptions = {
zoom: 12,
center: arena,
panControl: false,
zoomControl: false,
streetViewControl: false,
mapTypeControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
directionsDisplay.setMap(map);
var marker1 = new MarkerWithLabel({
position: arena,
draggable: false,
raiseOnDrag: false,
map: map,
icon: "images/lax-pin1.png",
labelContent: "Ted Reeve Arena",
labelAnchor: new google.maps.Point(25, 0),
labelClass: "pin", // the CSS class for the label
labelStyle: {opacity: 0.95}
});
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
}
function calcRoute() {
var request = {
origin: GeoMarker,
destination: marker1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</code>
The html is an onclick div tag for the calcRoute function
Thanks for any help....
There is an error reported:
TypeError: e is undefined
for line
map.setCenter(e.latLng);
Event listener
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
map.setCenter(e.latLng);
map.fitBounds(e.latLngBounds);
});
should be changed to
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function(e) {
//map.setCenter(e.latLng);
//map.fitBounds(e.latLngBounds);
map.setCenter(GeoMarker.getPosition());
map.fitBounds(GeoMarker.getBounds());
});
request should be changed to:
var request = {
origin: GeoMarker.getPosition(),
destination: marker1.getPosition(),
travelMode: google.maps.TravelMode.DRIVING
};
because origin/destination expects string or valid LatLng
Update: I forgot this change: marker1 has to be changed to global:
var map, GeoMarker;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var marker1;
Okay, I got it to work, but not pretty. This is what I did
function calcRoute() {
var arena1 = new google.maps.LatLng(43.684782688659126,-79.2992136269837);
var request = {
origin: GeoMarker.getPosition(),
destination: arena1,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});

Uncaught TypeError: Cannot read property 'text' of undefined Google Map [duplicate]

I try to make directions for my current position and marker coordinate. so i get latitude and longitude using getcurrentposition. then, i mark it.
function initialize() {
directionsDisplay = new google.maps.DirectionsRenderer();
var node = new google.maps.LatLng(-7.276442,112.791174);
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
directionsDisplay.setMap(map);
navigator.geolocation.getCurrentPosition(function(position) {
pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var marker = new google.maps.Marker({
position : pos,
map: map,
title:'Lokasi Anda'
});
var marker1 = new google.maps.Marker({
position : node,
map: map,
title:'Lokasi Anda'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
}
then, I calculate it using this function.
function calcRoute() {
var request = {
origin:pos,
destination:node,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
but why i can't see direction from pos to node. any suggestion ?
If I call the calcRoute function (and pass in the "pos" and "node" locations, it can't find directions between where I am (in the US) and where the point is located (Raya Its, Sukolilo, Surabaya City, East Java 60117, Republic of Indonesia). The DirectionsService returns a status of "ZERO_RESULTS".
ZERO_RESULTS No route could be found between the origin and destination.
working example
function calcRoute(pos,node) {
var directionsService = new google.maps.DirectionsService();
var request = {
origin:pos,
destination:node,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else { alert("Directions failed: "+status); }
});
}

Not giving me directions

I might not be understanding how this works, but if I enter in #Model.name which would find an address (just make one up for your testing purposes) the following javascript should find me, find the destination and find me directions.
But it doesn't. Why doesn't it? There are no console errors.
function success(position) {
var s = document.querySelector('#status');
if (s.className == 'success') {
// not sure why we're hitting this twice in FF, I think it's to do with a cached result coming back
return;
}
s.innerHTML = "found you!";
s.className = 'success';
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcanvas';
mapcanvas.style.height = '400px';
mapcanvas.style.width = '560px';
document.querySelector('article').appendChild(mapcanvas);
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 15,
center: latlng,
mapTypeControl: false,
navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcanvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "You are here! (at least within a " + position.coords.accuracy + " meter radius)"
});
var request = {
origin: latlng,
destination: '#Model.id',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function error(msg) {
var s = document.querySelector('#status');
s.innerHTML = typeof msg == 'string' ? msg : "failed";
s.className = 'fail';
// console.log(arguments);
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
error('not supported');
}
you must define the map-option for directionsDisplay

Function to determine if geo-location is enabled

I have a function that determines if the users broswer is geo-location enabled and if the user has geo-location enabled it is to display a Google map, if it isn't it then displays a different map.
function init_maps() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
} else {
noGeoInfo();
}
function geoInfo(position) {
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
directionsDisplay.setMap(map);
var request = {
origin: coords, //start point for directions
destination: '54.861283, -6.326805', //end point for directions
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
//}
function noGeoInfo() {
var location = new google.maps.LatLng(54.861283, -6.326805);
var mapOptions = {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
marker = new google.maps.Marker({
position: location,
map: map
});
}
}
}
The function init_maps() is called when the user clicks on a link. The problem is that nothing is displayed in the div when the page loads, if I remove:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo, { timeout: 20000 });
} else {
noGeoInfo();
}
function geoInfo(position) {
the map then loads as expected. Why is it not being displayed if I have the if else to determine if geo-location is enabled?

Google Maps not working on Chrome

I have a function that gives the user directions from their location to a fixed location on a map. It is being loaded in as external content to populate a main div, the map shows fine on both IE and Firefox but when I view it in Chrome it does not show. The Chrome dev console shows that the content is being loaded into the div and it is not putting out any errors.
External map.html
<script type="text/javascript" src="JS/location.js"></script>
<div id="mapContainer"></div>
<div id="writtenDir"></div>
JS to load content:
$('#Contact').click(function () {
$('#centerPane').load('External/map.html');
$.getScript("JS/location.js");
});
Location.js
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(geoInfo, noGeoInfo);
} else {
noGeoInfo();
}
function geoInfo(position) {
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById(''));
var request = {
origin: coords,
destination: '54.861283, -6.326805',
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
});
}
function noGeoInfo() {
var location = new google.maps.LatLng(54.861283, -6.326805);
var mapOptions = {
center: location,
zoom: 15, //Sets zoom level (0-21)
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapContainer"), mapOptions);
marker = new google.maps.Marker({
position: location,
map: map
});
}
Div to be loaded into:
<div id="centerPane" data-dojo-type="dijit/layout/ContentPane" data-dojo-props="region:'center'"></div>
Why is the map not showing in Google Chrome?
(live link, press "Contact Us" - http://scmweb.infj.ulst.ac.uk/~B00518833/DNA/View/index.php)
The problem resides inside the Nav.js file at line 59:
google.maps.event.trigger(map, 'resize');
The map is undefined when this line is executed.
Ensure that your js files are loaded in the right order and that the map is always defined before triggering the resize event.
I hope this helps.

Categories

Resources