If you wanted to represent geographical locations on Google map, You might need to draw the lines on Google map. Here in this article I'll explain how to draw the path among the locations by using Google map JavaScript API.
I'll create an array of locations in PHP and I'll also define the API key in PHP. Later I'll iterate every address and draw the path among all the locations.
You can change the center of the map by changing the latitude and longitude here:
1
|
var centerCoordinates = new google.maps.LatLng(28.6139, 77.2090);
|
You also can change the zoom level of the map here:
1
|
var defaultOptions = { center: centerCoordinates, zoom: 8 }
|
Here is the source code for drawing the path on Google map:
index.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
<?php
define("API_KEY", "AIzaSyDn1JrKoNqygrc0Wjei_wpPCSFIJXvvclk");
$addresses = ["Uttam Nagar West, New Delhi, Delhi","Meerut","Aligarh","Anupshahr","Bulandshahr"];
?>
<html>
<head>
<title>Draw Path on Google Map using Javascript API</title>
<style>
#map-layer {
max-width: 900px;
min-height: 550px;
}
</style>
</head>
<body>
<h1>Draw Path on Google Map using Javascript API</h1>
<div id="map-layer"></div>
<script>
var map;
var pathCoordinates = Array();
function initMap() {
var countryLength
var mapLayer = document.getElementById("map-layer");
var centerCoordinates = new google.maps.LatLng(28.6139, 77.2090);
var defaultOptions = { center: centerCoordinates, zoom: 8 }
map = new google.maps.Map(mapLayer, defaultOptions);
geocoder = new google.maps.Geocoder();
<?php
if (! empty($addresses)) {
?>
countryLength = <?php echo count($addresses); ?>
<?php
foreach ($addresses as $address)
{
?>
geocoder.geocode( { 'address': '<?php echo $address; ?>' }, function(LocationResult, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = LocationResult[0].geometry.location.lat();
var longitude = LocationResult[0].geometry.location.lng();
pathCoordinates.push({lat: latitude, lng: longitude});
new google.maps.Marker({
position: new google.maps.LatLng(latitude, longitude),
map: map,
title: '<?php echo $address; ?>'
});
if(countryLength == pathCoordinates.length) {
drawPath();
}
}
});
<?php
}
}
?>
}
function drawPath() {
new google.maps.Polyline({
path: pathCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1,
strokeWeight: 4,
map: map
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=<?php echo API_KEY; ?>&callback=initMap">
</script>
</body>
</html>
|
...