A Google Map API trouble,ask for support - html

I wrote a piece of code with Google Map to realize the location and GPS function.
But the navigation route always can't shows,I don't konw where is wrong?
Ask for help.Who can help me?
Thank you!
javascript code
<script type="text/javascript">
$( "#map-page" ).live( "pageinit", function() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var salon = new google.maps.LatLng(22.981666,120.194301);
var defaultLatLng = new google.maps.LatLng(22.983587,120.22599); // Default to Hollywood, CA when no geolocation support
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
calcRoute(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
console.log(error);
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
function drawMap(latlng) {
directionsDisplay = new google.maps.DirectionsRenderer();
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
directionsDisplay.setMap(map);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
var marker = new google.maps.Marker({
position:new google.maps.LatLng(22.981666,120.194301),
map:map,
title:"the salon"
});
}
function calcRoute(latlng) {
var start = latlng;
var end = new google.maps.LatLng(22.981666,120.194301);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
</script>

i have worked out
this piece of code is wrong
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
calcRoute(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
console.log(error);
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
i direct
// Location found, show map with these coordinates
drawMap(defaultLatLng);
calcRoute(defaultLatLng);

Related

Pass Google Maps SearchBox result to Directions Service

After reading documentation for the SearchBox class, the Places library including the AutoComplete class, and the Directions service, I cannot figure out how to pass the address selected by a user from the SearchBox to the Directions service to draw the map. The map and marker display correctly, and the SearchBox displays and functions correctly. On the "place_change" event, though, nothing happens. My code:
var rawlatitude = <?php echo $loc_lat; ?>;
var rawlongitude = <?php echo $loc_long; ?>;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude,longitude);
google.maps.event.addDomListener(window, 'load',initMap(latitude,longitude));
function initMap(lat,lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({map: map});
// listen to and respond to address search
var onChangeHandler = function() {
var location = searchBox.getPlaces();
var start = location.place_id;
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'place_change', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: start,
destination: latlong,
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if(status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
As Dr.Molle observed in his comment,
There is no place_changed-event for a SearchBox, it's an event for Autocomplete. The event for a SearchBox is called places_changed.
Also note that a SearchBox.getPlaces() returns an array with places
working fiddle
working code snippet:
var rawlatitude = 40.7127837;
var rawlongitude = -74.0059413;
var latitude = parseFloat(rawlatitude);
var longitude = parseFloat(rawlongitude);
var latlong = new google.maps.LatLng(latitude, longitude);
var viewport = {
"south": 40.4960439,
"west": -74.2557349,
"north": 40.91525559999999,
"east": -73.7002721
};
google.maps.event.addDomListener(window, 'load', function() {
initMap(40.735657, -74.1723667);
});
function initMap(lat, lng) {
// instantiate directions service object
var directionsService = new google.maps.DirectionsService;
// create map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 16,
center: latlong
});
// add marker
var marker = new google.maps.Marker({
position: latlong,
draggable: true,
map: map
});
// put address search box into map
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, {
bounds: viewport
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// create directions renderer and bind it to map
var directionsDisplay = new google.maps.DirectionsRenderer({
map: map
});
// listen to and respond to address search
var onChangeHandler = function() {
var locations = searchBox.getPlaces();
var start = locations[0].place_id;
var bounds = new google.maps.LatLngBounds();
bounds.extend(latlong);
bounds.extend(locations[0].geometry.location);
map.fitBounds(bounds);
var marker = new google.maps.Marker({
position: locations[0].geometry.location,
map: map,
title: locations[0].name
})
calculateAndDisplayRoute(directionsDisplay, directionsService, map, start);
};
google.maps.event.addListener(searchBox, 'places_changed', onChangeHandler);
}
function calculateAndDisplayRoute(directionsDisplay, directionsService, map, start) {
directionsService.route({
origin: {
placeId: start
},
destination: {
location: latlong
},
travelMode: google.maps.TravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<input id="pac-input" />
<div id="map"></div>

IBM Worklight 6.0 - Google maps fail to load while retrieving directions

I am using Google API v3 for "directions to here". However, the maps are not getting loaded properly. I am getting no error in logs.
When the page loads, I do the following:
var startPoint = new google.maps.LatLng(start.lat(), start.lng());
var endPoint = new google.maps.LatLng(parseFloat(end.latitude), parseFloat(end.longitude));
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
zoom: 15,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
center: endPoint
};
var map = new google.maps.Map(document.getElementById("branchLocatorSiteMapCanvas"), mapOptions);
$r.currentPage.map = map;
$page.off('pageshow').on('pageshow', function () {
// Suitable for V3 and fix for map div is not rendered
if ($r.currentPage.map) {
var timer = window.setTimeout(function () {
google.maps.event.trigger($r.currentPage.map, 'resize');
if (endPoint) {
$r.currentPage.map.setCenter(endPoint);
}
else if (startPoint) {
$r.currentPage.map.setCenter(startPoint);
}
window.clearTimeout(timer);
}, 400);
}
});
if ($r.currentPage.map) {
google.maps.event.addListenerOnce($r.currentPage.map, 'idle', function () {
// Do something only the first time the map is loaded
google.maps.event.trigger($r.currentPage.map, 'resize');
$r.currentPage.map.setCenter(endPoint);
});
I use this snippet for Direction Service and Rendering.
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
I didn't try it with your code example, but you can take this simpler demo project to see how to make it work in a Worklight 6.0.0.2-based app: Google Maps Directions Demo project.
The demo project is based on this example via the Google Maps documentation.
End result is:
JavaScript portion of the app:
var directionsDisplay = new google.maps.DirectionsRenderer();
var directionsService = new google.maps.DirectionsService();
var map;
function wlCommonInit(){
var chicago = new google.maps.LatLng(41.850033, -87.6500523);
var mapOptions = {
zoom: 7,
disableDefaultUI: false,
center: chicago
};
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
calcRoute();
}
function calcRoute() {
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}

error setting start point from geolocation calc route() gmaps v3

i use that code to have the geolocation in my app and it works good also when i'm moving. I added some few lines to create a calculation from the geolocation to an end (fixed) point with fixed lat-long. I don't understand why the origin point in my code is not accepted (fireBug says that i cannot call a property [object Object] on it) but i cannot figure out.
Here are the code about the gmaps v3:
//image for the marker
var imageLoc = '../../img/bbb3.gif'
var map;
//initialize the maps
function initialize() {
//call directionsService and Display for the route
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
//map option
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(44.49489, 11.34262),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
//create the marker for the geolocation
marker = new google.maps.Marker({
map: map,
icon: imageLoc
});
//call updatePos() function
updatePos();
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('panel'));
var request = {
//origin is the marker of my geolocation
origin: marker,
//destination is a fxed position
destination: new google.maps.LatLng(44.496099,11.340246),
travelMode: google.maps.DirectionsTravelMode.WALKING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
var i;
//here I set my marker (if i==0 -> first run)
function updatePos(){
var options = {
timeout: 60000, enableHighAccuracy: true
};
var myUpdatedPos = navigator.geolocation.watchPosition(onSuccess, onError, options);
function onSuccess(position) {
if (i==0){
marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
}
i++;
//here I update the position
newLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
marker.setPosition(newLatlng);
}
// onError Callback receives a PositionError object
//
function onError(error) {
alert('code: ' + error.code + '\n' +
'message: ' + error.message + '\n');
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Does anyne have idea why?
kind regards
Brus
The directionRequest takes either a string (an "address") or a google.maps.LatLng for origin and destination. marker is a google.maps.Marker object.
var request = {
//origin is the marker of my geolocation
origin: marker,
//destination is a fxed position
destination: new google.maps.LatLng(44.496099,11.340246),
travelMode: google.maps.DirectionsTravelMode.WALKING
};
To get the position of a marker, use its getPosition method:
var request = {
//origin is the marker of my geolocation
origin: marker.getPosition(),
//destination is a fxed position
destination: new google.maps.LatLng(44.496099,11.340246),
travelMode: google.maps.DirectionsTravelMode.WALKING
};
To give the marker a position when you initialize it, you can do this:
//create the marker for the geolocation
marker = new google.maps.Marker({
map: map,
position: map.getCenter(),
icon: imageLoc
});

Why won't google map navigate on my web page?

I want to locate a user's location using Geolocation and then navigate between user;s position and a fix point, but Google map just won't navigate and I am using the codes from Google's official documentation!
What's wrong? I am going mad after tried thousands of times,plz help
<script type="text/javascript">
$( "#map-page" ).live( "pageinit", function() {
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var salon = new google.maps.LatLng(22.981666,120.194301);
var defaultLatLng = new google.maps.LatLng(22.983587,120.22599); // Default to Hollywood, CA when no geolocation support
if ( navigator.geolocation ) {
function success(pos) {
// Location found, show map with these coordinates
drawMap(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
calcRoute(new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude));
}
function fail(error) {
console.log(error);
drawMap(defaultLatLng); // Failed to find location, show default map
}
// Find the users current position. Cache the location for 5 minutes, timeout after 6 seconds
navigator.geolocation.getCurrentPosition(success, fail, {maximumAge: 500000, enableHighAccuracy:true, timeout: 6000});
} else {
drawMap(defaultLatLng); // No geolocation support, show default map
}
function drawMap(latlng) {
var myOptions = {
zoom: 10,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
// Add an overlay to the map of current lat/lng
var marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Greetings!"
});
var marker = new google.maps.Marker({
position:new google.maps.LatLng(22.981666,120.194301),
map:map,
title:"the salon"
});
}
function calcRoute(latlng) {
var start = latlng;
var end = new google.maps.LatLng(22.981666,120.194301);
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
</script>
You forgot to setup directionsDisplay.

How to change the street view in google maps 3

Goal: Get the TEXT address and then display the street view and map view at the same time
Ref Site:
http://code.google.com/apis/maps/documentation/javascript/examples/streetview-simple.html
My site:
http://www.iamvishal.com/dev/property/P2154 (pls click the map view to see the map)
Problem: I am able to display the map and the address correctly but instreet view does not change. Any idea why ?
My js variable address hold the text address in this case "323235 Balmoral Terrace Heaton Newcastle Upon Tyne"
function initialize()
{
var fenway = new google.maps.LatLng(42.345573,-71.098326);
var mapOptions = {
center: fenway,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(
document.getElementById("map_canvas"), mapOptions);
var panoramaOptions = {
position: fenway,
pov: {
heading: 34,
pitch: 10,
zoom: 1
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById("pano"),
panoramaOptions);
map.setStreetView(panorama);
var geocoderTwo = new google.maps.Geocoder();
geocoderTwo.geocode({"address":address},function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker
({
map: map,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
}
);
}
Here's how I've created a streetview before:
function createStreetMap(strMapCanvasID, yourLatLng)
{
var panorama;
//once the document is loaded, see if google has a streetview image within 50 meters of the given location, and load that panorama
var sv = new google.maps.StreetViewService();
sv.getPanoramaByLocation(yourLatLng, 50, function(data, status) {
if (status == 'OK') {
//google has a streetview image for this location, so attach it to the streetview div
var panoramaOptions = {
pano: data.location.pano,
addressControl: false,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
}
};
var panorama = new google.maps.StreetViewPanorama(document.getElementById(strMapCanvasID), panoramaOptions);
// lets try and hide the pegman control from the normal map, if we're displaying a seperate streetview map
objCreatedMap.setOptions({
streetViewControl: false
});
}
else{
//no google streetview image for this location, so hide the streetview div
$('#' + strMapCanvasID).parent().hide();
}
});
}
Update: and you could call this function directly from within your existing code (I've amended the function to use a LatLng rather than individual latitude and longitude values:
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker
({
map: map,
position: results[0].geometry.location
});
createStreetMap('yourStreetViewDiv', results[0].geometry.location);
}
There are a couple issues with your code. Fix them first:
64 Uncaught ReferenceError: berkeley is not defined
Also, you'll need to set a zoom and mapTypeId options on your Map before anything shows.