google map api remove straight lines [duplicate] - google-maps

This question already has an answer here:
An issue while showing a path on Google Maps
(1 answer)
Closed 6 years ago.
I'm developing a MVC app using google map API.
There are 4 or more coordinates in my program. According to that I need to draw road path. This is my code so far.
<div id="dvMap" style="width: 500px; height: 500px">
</div>
#section scripts
{
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBZxYACsC1qz9gticRd4mbki9Tes9qexdw&sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Canberra',
"lat": '-35.2809',
"lng": '149.1300',
"description": ''
},
{
"title": 'Sydny',
"lat": '-33.8688',
"lng": '151.2093',
"description": ''
},
{
"title": 'Tamworth',
"lat": '-31.0927',
"lng": '150.9320',
"description": ''
}
,
{
"title": 'Brisbane',
"lat": '-27.465895',
"lng": '153.019519',
"description": ''
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), 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.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize 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) {
console.log('len ' + result.routes[0].overview_path.length)
for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
path.push(result.routes[0].overview_path[i]);
}
}
});
}
}
}
</script>
}
The problem is the map is shown straight lines as well.
I need to remove straight lines from the map (should keep lines draw on road path) and what's wrong in my code? In addition, Markers should show only for starting point and destination point. But all points are shown as markers. So how to do it...? Please give me a direction for doing it....

At the beginning of your script you're drawing markers on the map. To avoid that comment out the line map: map,
var marker = new google.maps.Marker({
position: myLatlng,
// map: map,
title: data.title
});
To remove the straight lines from the map:
comment out the line
//poly.setPath(path);
You need to use a DirectionsRenderer to show routes on the map once the routes are returned by the directionsService.
Define a function to render the computed routes
function renderDirections(result) {
var directionsRenderer = new google.maps.DirectionsRenderer;
directionsRenderer.setMap(map);
directionsRenderer.setDirections(result);
};
Add the rendering to the callback function of the directionsService
directionsService.route({
origin: src,
destination: des,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(result, status) {
// if route is computed successfully, render it on map
if (status == google.maps.DirectionsStatus.OK) {
console.log('len ' + result.routes[0].overview_path.length);
renderDirections(result);
} else {
console.log("Error: ", status);
}
});
The issue here is that you're trying to display multiple routes on your map, check this question for details.
Hope this helps.

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>

How to Zoom In further in google map to show markers clearly

I have got four markers which will be shown when i zoom in till the last .
The issue i am facing is that the markers one and four are overlapping with each other , and i cannot zoom zoom in further to click on them ?
Is there any solution for this without using Marker cluster??
some part of my code
function addMarker(response, lator, lonor, infowindow) {
if (response.length > 0) {
var global_markers = [];
for (var i = 0; i < response.length; i++) {
var lat = parseFloat(response[i].latitude);
var lng = parseFloat(response[i].longititude);
var dealername = response[i].name;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: "Dealer name: " + dealername,
icon: 'http://maps.google.com/mapfiles/marker.png'
});
global_markers[i] = marker;
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
}
}
}
This is my fiddle
http://jsfiddle.net/3VXTL/13/
Please let me know how to resolve this ??
One option is to make the markers smaller (use the "measle" little red do).
updated fiddle
code snippet:
var response = [{
"longititude": "78.377665",
"latitude": "17.439669",
"name": "one"
}, {
"longititude": "78.377617",
"latitude": "17.439692",
"name": "two"
}, {
"longititude": "78.377644",
"latitude": "17.439674",
"name": "three"
}, {
"longititude": "78.377665",
"latitude": "17.439667",
"name": "four"
}]
initializeCalllater(18.1124372, 79.01929969999999, response);
function initializeCalllater(lator, lonor, response) {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(lator, lonor);
var myOptions = {
zoom: 7,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: false,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
},
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.trigger(map, 'resize');
map.setCenter(new google.maps.LatLng(lator, lonor));
var infowindow = new google.maps.InfoWindow({});
addMarker(response, lator, lonor, infowindow);
}
function addMarker(response, lator, lonor, infowindow) {
if (response.length > 0) {
var global_markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < response.length; i++) {
var lat = parseFloat(response[i].latitude);
var lng = parseFloat(response[i].longititude);
var dealername = response[i].name;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
title: "Dealer name: " + dealername,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
bounds.extend(marker.getPosition());
global_markers[i] = marker;
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
}
map.fitBounds(bounds);
}
}
body,
html,
#map_canvas {
height: 100%;
width: 100%;
}
<script src="http://maps.google.com/maps/api/js"></script>
<div id="map_canvas" "></div>
If that is not enough, you could change the zIndex of the markers that overlap when you click on one of them (like this question: allow user to move marker position back (z-index?) in google maps custom map).

straight line is coming along with road map in google map API

I have one query regarding google map api .
I am drawing road map line between two Geo location(Suppose A and B) through one Geo point (Suppose C).
Problem is : First time when map is loaded there is always one straight line between point A and point B along with road map among these three points (A , B and C). But when map is reloaded again then straight line (Between A and B) vanishes as expected.
Could you please help me in this regard. My code is following.
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var markers = [
{
"title": 'Alibaug',
"lat": '28.4700',
"lng": '77.0300',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}
,
{
"title": 'Mumbai',
"lat": '28.6139',
"lng": '77.2090',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}
,
{
"title": 'Pune',
"lat": '28.5700',
"lng": '77.3200',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
];
window.onload = function () {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), 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[i]=myLatlng;
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
});
latlngbounds.extend(marker.position);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize 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];
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]);
}
} } );
} } }
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
Only send a single request. The Google Maps Directions Service supports waypoints if you have less than 10 total points (with the free API, 25 total points with Google Maps for Business), you can use a single request, with a source, a destination and a waypoint, which will reduce the load on Google servers and make the response more consistent.
One possible reason for the behavior you are seeing is the asynchronous behavior of the Directions Service. If the responses come back in a different order than they are sent, you could see the behavior you are describing.
proof of concept fiddle
code snippet:
window.onload = function() {
var mapOptions = {
center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
var infoWindow = new google.maps.InfoWindow();
var lat_lng = [];
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[i] = myLatlng;
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
latlngbounds.extend(marker.position);
}
map.setCenter(latlngbounds.getCenter());
map.fitBounds(latlngbounds);
//***********ROUTING****************//
//Initialize the Path Array
var path = new google.maps.MVCArray();
//Initialize 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
var request = {
travelMode: google.maps.DirectionsTravelMode.DRIVING
}
for (var i = 0; i < lat_lng.length; i++) {
if (i == 0) {
request.origin = lat_lng[i];
} else if (i == lat_lng.length - 1) {
request.destination = lat_lng[i];
} else {
if (!request.waypoints) {
request.waypoints = [];
}
request.waypoints.push({
location: lat_lng[i]
});
}
}
service.route(request, 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]);
}
poly.setPath(path);
}
});
};
var markers = [{
"title": 'Alibaug',
"lat": '28.4700',
"lng": '77.0300',
"description": 'Alibaug is a coastal town and a municipal council in Raigad District in the Konkan region of Maharashtra, India.'
}, {
"title": 'Mumbai',
"lat": '28.6139',
"lng": '77.2090',
"description": 'Mumbai formerly Bombay, is the capital city of the Indian state of Maharashtra.'
}, {
"title": 'Pune',
"lat": '28.5700',
"lng": '77.3200',
"description": 'Pune is the seventh largest metropolis in India, the second largest in the state of Maharashtra after Mumbai.'
}
];
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="dvMap" style="width: 500px; height: 500px">

Google Place API v3 with Sencha Touch 2.x

I am new to Sencha Touch, knows Javascript,jQuery,HTML5.
I am developing simple Google Map application with Sencha Touch + Sencha Architect where it place marker on current position and also use Google Place to find 'store'(i.e. types need for Google place search) near the current location. I am getting the locations in 'callbackPlaces' (i.e. latitude, longitude) but Google.Maps.Marker gives error in 'callbackPlaces' method (i.e. called through 'addMarker' method and I also tried and tested by putting Google.Maps.Marker in 'callbackPlaces').
Ext.define('MyApp.view.Map', {
extend: 'Ext.Map',
alias: 'widget.map',
config: {
useCurrentLocation: true,
listeners: [
{
fn: 'onMapMaprender',
event: 'maprender'
}
]
},
onMapMaprender: function(map, gmap, options) {
this.initializePlaces();
},
initializePlaces: function() {
//Set Marker on Current Position
var geo = this.getGeo();
var currentPosition = new google.maps.LatLng(geo.getLatitude(), geo.getLongitude());
this.createMarker(currentPosition);
//request set for Places Services
var request = {
location: currentPosition,
radius: 500,
types: ['store']
};
this.getMap().zoom = 15;
// Call PlacesService
var service = new google.maps.places.PlacesService(this.getMap());
service.nearbySearch(request, this.callbackPlaces);
},
callbackPlaces: function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
addMarker(results[i]);
}
}
},
createMarker: function(position) {
//Here Position = Google Map LatLng
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: this.getMap(),
position: position
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.setContent("Lng: " + marker.position.lng() + "\n Lat: " + marker.position.lat());
infoWindow.open(this.getMap(), marker);
});
},
addMarker: function() {
//Here Place = google.maps.places
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: this.getMap(),
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.setContent("Lng: " + marker.position.lng() + "\n Lat: " + marker.position.lat());
infoWindow.open(this.getMap(), marker);
});
}
});
I don't know what went wrong!
Any help|hint would appreciated!
Thanks in advance.
You pointed out there was a scope issue in the callbackPlaces function.
Therefore you should replace the following line:
service.nearbySearch(request, this.callbackPlaces);
with
service.nearbySearch(request, function (results, status) {
this.callbackPlaces.call(this, [results, status]);
});
Hope this helps

Google Maps API v3 multiple markers Infowindow

I've used the code below to display a map with multiple markers and infowindows. Now I have encountered the very common problem of the last infowindow showing up on all markers. I've tried all sorts of solutions including: http://you.arenot.me/2010/06/29/google-maps-api-v3-0-multiple-markers-multiple-infowindows/ and this one http://www.robertbolton.com/blog/google-maps-v3-multiple-markers-and-infowindows-in-a-loop but none of them fix the problem.
Here is my code:
var infowindow = null;
var geocoder;
var map;
$(document).ready(function() {
initialize();
});
function initialize() {
var myOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
scrollwheel: false
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
setMarkers(map, people);
infowindow = new google.maps.InfoWindow({
content: "loading..."
});
}
var people = [
{"userid":"47","lastname":"lastname1","firstname":"firstname1","address":"Paris, France","phone1":"00000000000","phone2":"","email":"me#me.com"},
{"userid":"42","lastname":"lastname2","firstname":"firstname2","address":"Versaille, France","phone1":"0","phone2":"0","email":"me#me.com"}
];
function setMarkers(map, people) {
for (var i = 0; i < people.length; i++) {
var p = people[i];
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
geocoding is an asynchronous request. So when you use geocoding inside the for-loop, the loop is already finished when you receive the results, i will always be 1 and point to the last item of people.
What you can do: split the marker-creation into 2 functions. 1 for the loop which calls the 2nd function that creates the markers:
remove the current function setMarkers and add the following 2 functions to your script:
function setMarkers(map,people) {
for (var i = 0; i < people.length; i++) {
setMarker(map, people[i])
}
}
function setMarker(map, people) {
var p=people;
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': p["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
position: results[0].geometry.location,
map: map,
html: p["address"]
});
var contentString = "Some content";
google.maps.event.addListener(marker, "click", function () {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
The rest of your script may stay as it is.