我有两个文本框来源和目的地以及谷歌自动完成功能,其中用户将定义他/她的旅行路径,我将在google地图上显示路径,并在源和目标之间绘制线条。
我动态生成5个文本框,其中我绑定谷歌 自动完成此动态生成的文本框功能,用户可以在其中定义5个点 这是源和目的地之间的城市,我想表明 所有这五点都在我的来源和目的地的那一行。
在这个动态生成过程中,用户也可以从任何位置删除文本框,我想从我的谷歌地图路径中删除这些点从源到目的地。
现在我的来源和目的地就是这样假设:
来源:孟买
目标:艾哈默德巴德
我的第一个动态Texbox输入:Nashik
然后这个nashik不会出现在孟买和艾哈迈达巴德之间的路径上,这个路径不在我的来源和目的地的线上,我想要 nashik 那些蓝线我的孟买和 ahmedabad
源代码:未在此小提琴中运行,请检查此plunker是否正常运行:Running demo
google.maps.event.addDomListener(window, 'load', function() {
var places = new google.maps.places.Autocomplete(document.getElementById('source'));
google.maps.event.addListener(places, 'place_changed', function() {
var place = places.getPlace();
});
var places1 = new google.maps.places.Autocomplete(document.getElementById('destination'));
google.maps.event.addListener(places1, 'place_changed', function() {
var place1 = places1.getPlace();
});
});
var location1;
var location2;
var address1;
var address2;
var latlng;
var geocoder;
var map;
var line;
var infowindow1;
var infowindow2;
var distance;
// finds the coordinates for the two locations and calls the showMap() function
function initialize() {
// $("#googlemapview").show();
geocoder = new google.maps.Geocoder(); // creating a new geocode object
// getting the two address values
address1 = document.getElementById("source").value;
address2 = document.getElementById("destination").value;
// finding out the coordinates
if (geocoder) {
geocoder.geocode({
'address': address1
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//location of first address (latitude + longitude)
location1 = results[0].geometry.location;
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
geocoder.geocode({
'address': address2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
//location of second address (latitude + longitude)
location2 = results[0].geometry.location;
// calling the showMap() function to create and show the map
showMap();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
}
// creates and shows the map
function showMap() {
// center of the map (compute the mean value between the two locations)
latlng = new google.maps.LatLng((location1.lat() + location2.lat()) / 2, (location1.lng() + location2.lng()) / 2);
// get the map type value from the hidden field
var maptype = document.getElementById("maptype").value;
var typeId;
if (maptype == "roadmap")
typeId = google.maps.MapTypeId.ROADMAP;
else if (maptype == "hybrid")
typeId = google.maps.MapTypeId.HYBRID;
else if (maptype == "satellite")
typeId = google.maps.MapTypeId.SATELLITE;
else if (maptype == "terrain")
typeId = google.maps.MapTypeId.TERRAIN;
// set map options
// set zoom level
// set center
// map type
var mapOptions = {
zoom: 1,
center: latlng,
mapTypeId: typeId
};
// create a new map object
// set the div id where it will be shown
// set the map options
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// event listener to update the map type
google.maps.event.addListener(map, 'maptypeid_changed', function() {
maptype = map.getMapTypeId();
document.getElementById('maptype').value = maptype;
});
// create the markers for the two locations
var marker1 = new google.maps.Marker({
map: map,
position: location1,
title: "First location",
draggable: true
});
var marker2 = new google.maps.Marker({
map: map,
position: location2,
title: "Second location",
draggable: true
});
// create the text to be shown in the infowindows
var text1 = '<div id="content">' +
'<h1 id="firstHeading">First location</h1>' +
'<div id="bodyContent">' +
'<p>Coordinates: ' + location1 + '</p>' +
'<p>Address: ' + address1 + '</p>' +
'</div>' +
'</div>';
var text2 = '<div id="content">' +
'<h1 id="firstHeading">Second location</h1>' +
'<div id="bodyContent">' +
'<p>Coordinates: ' + location2 + '</p>' +
'<p>Address: ' + address2 + '</p>' +
'</div>' +
'</div>';
// create info boxes for the two markers
infowindow1 = new google.maps.InfoWindow({
content: text1
});
infowindow2 = new google.maps.InfoWindow({
content: text2
});
// add action events so the info windows will be shown when the marker is clicked
google.maps.event.addListener(marker1, 'click', function() {
infowindow1.open(map, marker1);
});
google.maps.event.addListener(marker2, 'click', function() {
infowindow2.open(map, marker2);
});
// add action events for dragging the markers
google.maps.event.addListener(marker1, 'dragend', function() {
location1 = marker1.getPosition();
drawRoutes(location1, location2);
});
google.maps.event.addListener(marker2, 'dragend', function() {
location2 = marker2.getPosition();
drawRoutes(location1, location2);
});
// initialize directions service
directionsService = new google.maps.DirectionsService();
directionsDisplay = new google.maps.DirectionsRenderer({
suppressMarkers: true,
suppressInfoWindows: true
});
directionsDisplay.setMap(map);
drawRoutes(location1, location2);
}
function drawRoutes(location1, location2) {
// show new addresses
geocoder = new google.maps.Geocoder(); // creating a new geocode object
if (geocoder) {
geocoder.geocode({
'latLng': location1
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
address1 = results[0].formatted_address;
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
if (geocoder) {
geocoder.geocode({
'latLng': location2
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
address2 = results[0].formatted_address;
continueShowRoute(location1, location2);
}
} else {
alert("Geocoder failed due to: " + status);
}
});
}
}
function continueShowRoute(location1, location2) {
// hide last line
if (line) {
line.setMap(null);
}
// show a line between the two points
line = new google.maps.Polyline({
map: map,
path: [location1, location2],
strokeWeight: 7,
strokeOpacity: 0.8,
strokeColor: "#FFAA00"
});
// find and show route between the points
var request = {
origin: location1,
destination: location2,
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
} else {
alert('error: ' + status);
}
});
// update text in infowindows
var text1 = '<div id="content">' +
'<h1 id="firstHeading">First location</h1>' +
'<div id="bodyContent">' +
'<p>Coordinates: ' + location1 + '</p>' +
'<p>Address: ' + address1 + '</p>' +
'</div>' +
'</div>';
var text2 = '<div id="content">' +
'<h1 id="firstHeading">Second location</h1>' +
'<div id="bodyContent">' +
'<p>Coordinates: ' + location2 + '</p>' +
'<p>Address: ' + address2 + '</p>' +
'</div>' +
'</div>';
infowindow1.setContent(text1);
infowindow2.setContent(text2);
}
var cnt = 1;
var autocomplete = [];
var markerPostion = [];
var map = null;
var marker = [];
var usedIds = [];
var geocoder;
var maxNumberOfTextboxAllowed = 5;
var autocompleteOptions = {
componentRestrictions: { country: "in" }
};
function findAvailableId() {
var i = 1;
while (usedIds[i]) i++;
usedIds[i] = true;
return i;
};
function removeId(idToRemove) {
usedIds[idToRemove] = false;
};
function GenerateSourceDestinationPoint() {
if (cnt <= maxNumberOfTextboxAllowed) {
var id = findAvailableId();
var OrderingField = $("<div class='OrderingField' id='OrderingField" + id + "'/>");
var LeftFloat = $("<div class='LeftFloat' id='LeftFloat" + id + "'/>");
var RightFloatCommands = $("<div class='RightFloat Commands' id='RightFloat Commands" + id + "'/>");
var upButton = $("<button id='navigate' value='up'>Up</button>");
var downButton = $("<button id='navigate' value='down'>Down</button>");
var fName = $("<input type='text' class='fieldname' id='Txtopt" + id + "' name='TxtoptNm" + id + "'/>");
var removeButton = $("<img class='remove' src='../remove.png' />");
LeftFloat.append(fName);
LeftFloat.append(removeButton);
RightFloatCommands.append(upButton);
RightFloatCommands.append(downButton);
OrderingField.append(LeftFloat);
OrderingField.append(RightFloatCommands);
$("#FieldContainer").append(OrderingField);
var newInput = [];
var newEl = document.getElementById('Txtopt' + id);
newInput.push(newEl);
setupAutocomplete(autocomplete, newInput, 0);
cnt = cnt + 1;
}
else
alert("Cant create more than 5 points")
}
$(document).on('click', "img.remove", function () {
$(this).parent().parent().fadeOut(1000, function () {
if (cnt > maxNumberOfTextboxAllowed)
cnt = cnt - 2;
else if (cnt == 1)
cnt = 1;
else
cnt = cnt - 1;
var id = $(this).attr("id").substr(13);
removeId(id);
$(this).remove();
});
});
function setupAutocomplete(autocomplete, inputs, i) {
autocomplete.push(new google.maps.places.Autocomplete(inputs[i], autocompleteOptions));
var idx = autocomplete.length - 1;
google.maps.event.addListener(autocomplete[idx], 'place_changed', function () {
if (marker[idx] && marker[idx].setMap) {
marker[idx].setMap(null);
marker[idx] = null;
}
marker[idx] = new google.maps.Marker({
map: map,
icon: 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=' + '|FF776B|000000'
});
marker[idx].setVisible(false);
var place = autocomplete[idx].getPlace();
if (!place.geometry) {
return;
}
marker[idx].setPosition(place.geometry.location);
marker[idx].setVisible(true);
});
}
html,
body,
#map_canvas {
height: 100% !important;
margin: 0 !important;
padding: 0 !important;
}
#panel {
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
}
/*
Provide the following styles for both ID and class,
where ID represents an actual existing "panel" with
JS bound to its name, and the class is just non-map
content that may already have a different ID with
JS bound to its name.
*/
#panel,
.panel {
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
#panel select,
#panel input,
.panel select,
.panel input {
font-size: 15px;
}
#panel select,
.panel select {
width: 100%;
}
#panel i,
.panel i {
font-size: 12px;
}
ul.messages_layout li.left {
padding-left: 7px !important;
}
.gmnoprint img {
max-width: none;
}
.LeftFloat {
float: left;
}
.RightFloat {
float: right;
}
.FieldContainer {
border: 1px solid black;
width: 400px;
height: 300px;
overflow-y: auto;
font-family: tahoma;
}
.OrderingField {
margin: 3px;
border: 1px dashed #0da3fd;
background-color: #e8efff;
height: 50px;
}
.OrderingField div.Commands {
width: 60px;
}
/*button {
width: 60px;
}*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places,geometry"></script>
<input id="maptype" type="hidden" value="roadmap" />
<input type="button" onclick="initialize()" value="View on Google Map" />
<br />
<br />
<label>Source</label>
<input type="text" value="" name="source" id="source">
<br />
<br />
<label>Destination</label>
<input type="text" value="" name="destination" id="destination">
<br />
<br />
<button onclick="GenerateSourceDestinationPoint()" class="btn btn-primary" type="button">Add Points</button>
<div style="border: 1px solid -moz-nativehyperlinktext;"></div>
<div id="FieldContainer">
</div>
<br />
<br />
<div>
<div id="map_canvas"></div>
</div>