drawing multiple lines in google-map - javascript

i've drawn a single polyline in google-map, but when tried to draw two line in single map it failed...its not showing anything on the google-map
can anyone please tell me some solution for this
SEE - http://jsfiddle.net/wLeBh/12/
My javascript is as given below
function initMap()
{
alert("entered!!!");
var routes = [{origin:'p t usha road, kozhikode',
destination:'cooperative hospital, eranjipalam, kozhikode'
},
{origin:'IIM, Kozhikode',
destination:'VELLIMADUKUNNU, KOZHIKODE'
}
];
try{
var rendererOptions = {
preserveViewport: true,
suppressMarkers:true,
routeIndex:1
};
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
//routes.each(function(route){
for (var i = 0, l = routes.length; i < l; i++) {
var obj = routes[i];
alert(obj.origin);
var request = {
origin: obj.origin,
destination: obj.destination,
travelMode: google.maps.TravelMode.DRIVING
};
map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(0,0),
zoom: 10,
maxZoom:16,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions:
{
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
},
navigationControl: true,
navigationControlOptions:
{
style: google.maps.NavigationControlStyle.SMALL
}
});
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
directionsDisplay.setMap(map);
directionsService.route(request, function(result, status) {
console.log(result);
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
}catch(e){alert(e);}
}

There are some issues not related to the question:
you create a new Map-instance on each iteration
you didn't set the map-property of the Renderer
you've set the routeIndex to 1, but you get only 1 route(with the index 0)
The issue related to the question: The attempt was good, but the implementation wasn't.
You must create a new DirectionsRenderer-instance for each request(you've done it), but this instance is visible in the function-scope, so the variable will be overwritten on each iteration and when the response arrives each response will use the same DirectionsRenderer-instance(which may only render a single route).
Use a anonymous function to create the DirectionsRenderer-instances and requests:
$.each(routes,
function(i,obj){//<--anonymous function
var request = {
origin: obj.origin,
destination: obj.destination,
travelMode: google.maps.TravelMode.DRIVING
},
//directionsDisplay is only visible in the scope of this anonymous function
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
});});
Fiddle: http://jsfiddle.net/doktormolle/wLeBh/14/

Related

Map: Expected mapDiv of type Element but was passed undefined - google maps

I have a map inside a div with a reference #mapa
When i want to trace a route in the map the map refreshes. I want to not refresh the map i have the following code:
<div style="height: 500px; width: auto;" #mapa>
<google-map height="500px" width="100%" [zoom]="zoom" [center]="center" [options]="options" (mapClick)="click($event)">
<map-marker #markerElem *ngFor="let marker of markers" [position]="marker.position" [label]="marker.label" [title]="marker.title" [options]="marker.options" (mapClick)="openInfo(markerElem, marker.info)" (mapDragend)="moveMap($event)">
</map-marker>
<map-info-window>{{ infoContent }}</map-info-window>
</google-map>
</div>
If i remove the div with the reference #mapa and i put it the reference into the <google-map> tag i got the title error and show the map without routes.
trazarRutaMapa() {
const directionsService = new google.maps.DirectionsService;
const directionsDisplay = new google.maps.DirectionsRenderer;
const map = new google.maps.Map(this.mapa.nativeElement, {
zoom: 7,
center: {
lat: this.markers[0].position.lat,
lng: this.markers[0].position.lng
}
});
directionsDisplay.setMap(map);
directionsDisplay.setOptions({
suppressMarkers: false,
draggable: true,
markerOptions: {
icon: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
}
});
directionsService.route({
origin: {
lat: this.markers[0].position.lat,
lng: this.markers[0].position.lng
},
destination: {
lat: this.markers[1].position.lat,
lng: this.markers[1].position.lng
},
travelMode: google.maps.TravelMode.DRIVING,
}, (response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
console.log('ESTATUS OKEY');
directionsDisplay.setDirections(response);
} else {
window.alert("Fallo el estatus" + status);
}
});
}
As far as I can see you can accomplish your goal just using the #angular/google-maps official module.
Your HTML will become something like this
<google-map [options]="options">
<map-marker *ngFor="let some of somearray" [icon]="...", [label]="...", [position]="..."></map-marker>
<map-directions-renderer [directions]="..." [options]="..."></map-directions-renderer>
</google-map>
and your trazarRoutaMapa() method will become something like this:
trazarRoutaMapa(): void {
const directionsService = new google.maps.DirectionsService; // better if injected from constructor
const request: google.maps.DirectionsRequest = {
destination: {
lat: this.markers[0].position.lat,
lng: this.markers[0].position.lng
},
origin: {
lat: this.markers[1].position.lat,
lng: this.markers[1].position.lng
},
travelMode: google.maps.TravelMode.DRIVING
};
return directionsService.route(
request,
(response, status) => {
if (status === google.maps.DirectionsStatus.OK) {
console.log('ESTATUS OKEY');
directionsDisplay.setDirections(response);
} else {
window.alert("Fallo el estatus" + status);
}
});
}
Disclaimer: I didn't test the code, just created on notepad copy/pasting :)

Uncaught TypeError: Cannot read property 'apply' of undefined Google Maps

I am using Google Maps to make markers on a map and I am trying to convert addresses to geocodes using the following code:
<script src="https://maps.googleapis.com/maps/api/js?key=&callback=initialize" async defer></script>
<script type="text/javascript">
var map;
function initialize() {
var chamberLocation = {lat: 43, lng: -82};
var geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 42.9745, lng: -82.4066},
zoom: 14,
styles: [{"featureType":"road","elementType":"geometry","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","stylers":[{"hue":149},{"saturation":-78},{"lightness":0}]},{"featureType":"road.highway","stylers":[{"hue":-31},{"saturation":-40},{"lightness":2.8}]},{"featureType":"poi","elementType":"label","stylers":[{"visibility":"off"}]},{"featureType":"landscape","stylers":[{"hue":163},{"saturation":-26},{"lightness":-1.1}]},{"featureType":"transit","stylers":[{"visibility":"off"}]},{"featureType":"water","stylers":[{"hue":3},{"saturation":-24.24},{"lightness":-38.57}]}],
zoomControl: false,
scaleControl: false,
mapTypeControl: false,
disableDefaultUI: false,
streetViewControl: false,
rotateControl: false,
scrollwheel: false,
draggable: false
});
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
var address = 'place';
geocoder.geocode({ 'address' : address }), function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
console.log('This didnt work' + status);
}
};
}
</script>
Whenever I do this I get an error saying Uncaught TypeError: Cannot read property 'apply' of undefined
What is causing this error? I am unsure as to how to fix this. Do I have to import another google maps api?
The error is a typo. I put the code below and commented //change in places where the typo was at. geocoder.geocode({}, callback) is a function that takes an object and a callback, but you have geocoder.geocode({ 'address' : address }), the typo is the ) it should be geocoder.geocode({ 'address' : address }, function(results, status) { ...
<div id="map" style="width: 320px; height: 480px;"></div>
<script type="text/javascript">
var map;
function initialize() {
// your code
// etc ...
codeAddress(geocoder, map);
}
function codeAddress(geocoder, map) {
var address = 'place';
geocoder.geocode({
'address': address
}, // change
function(results, status) {
if (status == 'OK') { // change
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
// some debug output
console.log("status is: " + status)
console.log("results is: " + JSON.stringify(results[0].geometry.location))
} else {
console.log('This didnt work' + status);
}
});
};
</script>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=API_KEY&callback=initialize"></script>
Today i have also faced the same error while using distance matrix library, what we need to do is simply use the callback function mentioned here https://developers.google.com/maps/documentation/javascript/distancematrix
According to this doc https://developers.google.com/maps/documentation/javascript/examples/distance-matrix#maps_distance_matrix-typescript i was using promises thats when i encounterd the above error
var origin1 = new google.maps.LatLng(55.930385, -3.118425);
var origin2 = 'Greenwich, England';
var destinationA = 'Stockholm, Sweden';
var destinationB = new google.maps.LatLng(50.087692, 14.421150);
var service = new google.maps.DistanceMatrixService();
service.getDistanceMatrix(
{
origins: [origin1, origin2],
destinations: [destinationA, destinationB],
travelMode: 'DRIVING',
transitOptions: TransitOptions,
drivingOptions: DrivingOptions,
unitSystem: UnitSystem,
avoidHighways: Boolean,
avoidTolls: Boolean,
}, callback);
function callback(response, status) {
// See Parsing the Results for
// the basics of a callback function.
console.log(status);
console.log(response);
}

Why can't the route be dragged when setting draggable = true?

I think this is a very simple problem. But I have not found the reason.
My code is like this:
var request = {
origin: new google.maps.LatLng(startLat, startLng),
destination: new google.maps.LatLng(targetLat, targetLng),
waypoints: stopovers,
travelMode: google.maps.DirectionsTravelMode.DRIVING,
provideRouteAlternatives: true
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var rendererOptions = {
map: map,
suppressMarkers: true,
draggable: true
}
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
directionsDisplay.setOptions({
polylineOptions: {
strokeColor: colors[i]
}
});
directionsDisplay.setDirections(response);
} else
console.log("error " + status);
});
When the route is displayed on the map, I can find the "point" which is used to drag the route.
But if I really drag the route, the route will recover to its original status after I release the mouse button.
Did anyone have the similar problem?
You might have a problem with the usage of : waypoints: stopovers, in your code please refer to https://developers.google.com/maps/documentation/javascript/directions#DirectionsRequests. If we had a fiddle we'd work on that, but till then please take a look at this fiddle that I created for you using and articles code taken from this article which seems to define the rendererOptions in a higher level:
var map;
var rendererOptions = {draggable: true};
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();
$(document).ready(function () {
//draw a map centered at Empire State Building Newyork
var latlng = new google.maps.LatLng(40.748492, -73.985496);
var myOptions = {
zoom: 15,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("divDirections"));
$("#btnGetDirections").click(function(){
calcRoute($("#txtAddress1").val(),$("#txtAddress2").val());
});
});
function calcRoute(start,end) {
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING,
provideRouteAlternatives : false
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}

Sencha Touch: Can't get map object from Ext.Map to give to the google directions service

I have a Ext.Map object that I am trying to get the google.maps.map() object from, but it's not returning a valid object, so I can't render the directions on the map.
addMaps: function(options){
directionsDisplay =new google.maps.DirectionsRenderer();
directionsService = new google.maps.DirectionsService();
activeMarkers = new Array();
uconnPosition = new google.maps.LatLng(41.809929, -72.25486);
myMapPosition = new google.maps.LatLng(41.809929, -72.25486);
curBuildingPosition = new google.maps.LatLng(41.809929, -72.25486);
uconnMap = new Ext.Map({
mapOptions : {
center : new google.maps.LatLng(41.809929, -72.25486), //UConn
zoom : 16,
mapTypeId : google.maps.MapTypeId.ROADMAP,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
}
},
plugins : [
new Ext.plugin.GMap.Tracker({
trackSuspended : true, //suspend tracking initially
highAccuracy : false,
marker : new google.maps.Marker({
position: uconnPosition,
title : 'My Current Location',
shadow: shadow,
icon : image
})
})
]
});
UConnApp.views.uconnTourMainPanel.add(uconnMap);
directionsDisplay.setMap(uconnMap.getMap()); //THIS IS WHERE I THINK THE PROBLEM IS
var org = new google.maps.LatLng(41.806501, -72.252769);
var dest = new google.maps.LatLng(41.805222,-72.254388);
var request = {
origin: org,
destination:dest,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
})
},
So the map is created without issue, but when I try to send the map object to the Google Maps directions service, it won't render to my map. I have tried both uconnMap.getMap() and uconnMap.map, but have not gotten an object back from either that the direction service renders to. Could anyone help me please?
You need to use the following code ::
UConnApp.views.uconnTourMainPanel.add(uconnMap);
directionsDisplay.setMap(uconnMap.map); // Changed this line for you…
var org = new google.maps.LatLng(41.806501, -72.252769);
var dest = new google.maps.LatLng(41.805222,-72.254388);
var request = {
origin: org,
destination:dest,
travelMode: google.maps.TravelMode.WALKING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
})
Now everything works fine. I just tested it out in my app for you :)

Detect the user current location,add a marker onto that position in Sencha Touch V2

The code below facilitates a map to be displayed with markers added onto it from data in a JSON file.The getDirections from one marker to another has also been facilitated.
Need to:Detect the user current location,add a marker onto that position and apply that location to the start variable given within the code below so that directions from that current position to the marker that has been tapped can be plotted.
Ext.define('Navigator.view.mapcard', {
extend: 'Ext.Map',
xtype: 'mapcard',
config: {
title: 'Mappa',
iconCls: 'maps',
// useCurrentLocation: true,
mapOptions: {
center: new google.maps.LatLng('24.859622', '18.84089'),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP,
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.DEFAULT
}
},
listeners: {
maprender: function (comp, map) {
var data = Ext.getStore('Contacts'),
marker = [], infowindow = [],
dist = [];
data.on('load', function () {
data.each(function (rec, idx, cnt) {
var latLng = new google.maps.LatLng(rec.get('latitude'), rec.get('longitude'));
marker[idx] = new google.maps.Marker({
map: map,
position: latLng
}),
infowindow[idx] = new google.maps.InfoWindow({
content: rec.get('title')
});
google.maps.event.addListener(marker[idx], 'click', function () {
infowindow[idx].open(map, marker[idx]);
if (dist.length === 0) {
dist.push(rec.get('title'));
} else if (dist.length === 1) {
dist.push(rec.get('title'));
} else if (dist.length > 1) {
// need reload map
dist = [];
dist.push(rec.get('title'));
}
if (dist.length === 2) {
var start = dist[0],
end = dist[1],
request = {
origin: start,
destination: end,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
var directionsDisplay = new google.maps.DirectionsRenderer(),
directionsService = new google.maps.DirectionsService();
directionsDisplay.setMap(map);
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
});
//setTimeout(function () { map.panTo(latLng) }, 1000);
});
});
}
}
}
});

Categories

Resources