google maps draw a line between two points - javascript

I am getting the latitude/longitude from the DB. I am unable to draw a line between two distances. Here is my code
var auto_refresh = setInterval(
function () {
$.get('http://developer.allsecure.me/Location/longlat', function (data) {
map_canvas.setCenter(new google.maps.LatLng(data.startlat, data.startlong));
clearMarkers();
setMarker(map_canvas, 'center', new google.maps.LatLng(data.startlat, data.startlong), '', '/img/device.png', '', '', true);
var line = new google.maps.Polyline({
path: [new google.maps.LatLng(data.startlat, data.startlong), new google.maps.LatLng(data.endlat, data.endlong)],
strokeColor: "#FF0000",
strokeOpacity: 1.0,
strokeWeight: 10,
map: map
});
}, 'json');
}, 1000);
I don't know why it isn't adding the polylines between the two distances.

As the comment above was the actual solution
When you define the line you use map: map shouldn't this be map: map_canvas?

Related

How to get lat long on draggable polygons? [duplicate]

This question already has an answer here:
How can I detect when an editable polygon is modified?
(1 answer)
Closed 4 years ago.
I want to get Lat and Long when I drag or edit polygon. How i can apply event listeners to this polygone so that whenever i edit or drag polygone it should show lat long on console of every point which i edit on polygon.
function initialize() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: {lat: 51.476706, lng: 0},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// create an array of coordinates for a pentagonal polygon
var arrCoords = [
new google.maps.LatLng(51.474821, -0.001935),
new google.maps.LatLng(51.474647, 0.003966),
new google.maps.LatLng(51.477708, 0.004073),
new google.maps.LatLng(51.479753, 0.000468),
new google.maps.LatLng(51.477654, -0.002192)
];
var polygon = new google.maps.Polygon({
editable: true,
paths: arrCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
first make geodesic: true with draggable: true in polygon
When enabling dragging on a polygon or polyline, you should also
consider making the polygon or polyline geodesic, by setting its
geodesic property to true
Ref: https://developers.google.com/maps/documentation/javascript/shapes
insert_at & set_at gonna be called when polyline get edited.
var polygon = new google.maps.Polygon({
editable: true,
paths: arrCoords,
strokeColor: "#FF0000",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#FF0000",
fillOpacity: 0.35,
map: map,
draggable: true,
geodesic: true
});
google.maps.event.addListener(polygon, 'dragend', function(evt){
console.log(evt.latLng.lat() ,'--', evt.latLng.lng() );
});
google.maps.event.addListener(polygon.getPath(), 'insert_at', function(index, obj) {
console.log('Vertex removed from inner path.');
console.log(obj.lat() ,'--', obj.lng() );
});
google.maps.event.addListener(polygon.getPath(), 'set_at', function(index, obj) {
console.log('Vertex moved on outer path.');
console.log(obj.lat() ,'--', obj.lng() );
});

Google Maps Api: cannot click on clickable polygon behind datalayer

Hi I am using google maps api(JavaScript) to build an interactive world map. It went really well until I ran into this problem. I am using polygons to show to outline of a country. These polygons trigger a modal showing information about the country when clicked on. This worked until I started to use "Data Layer: Earthquake data". Instead of using earthquake data I use sales information of the company I work at. So if a large share of our customers are from the Netherlands then the datalayer assigned to the Netherlands will be very large. The problem is that because of the datalayers the countries are no longer clickable. I can not click "through" the datalayer. Is there a possibility that I can trigger the event behind the datalayer?
This code displays the datalayers:
map.data.loadGeoJson('./data/test.json');
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0
}
})
});
map.data.addListener('mouseover', function(event) {
map.data.overrideStyle(event.feature, {
title: 'Hello, World!'
});
});
map.data.addListener('mouseout', function(event) {
map.data.revertStyle();
});
function eqfeed_callback(data) {
map.data.addGeoJson(data);
}
This code displays the polygons:
function drawMap(data) {
var rows = data['rows'];
for (var i in rows) {
if (rows[i][0] != 'Antarctica') {
var newCoordinates = [];
var geometries = rows[i][1]['geometries'];
if (geometries) {
for (var j in geometries) {
newCoordinates.push(constructNewCoordinates(geometries[j]));
}
} else {
newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
}
var country = new google.maps.Polygon({
paths: newCoordinates,
strokeColor: 'transparent',
strokeOpacity: 1,
strokeWeight: 0.3,
fillColor: '#cd0000',
fillOpacity: 0,
name: rows[i][0]
});
google.maps.event.addListener(country, 'mouseover', function() {
this.setOptions({
fillOpacity: 0.3
});
});
google.maps.event.addListener(country, 'mouseout', function() {
this.setOptions({
fillOpacity: 0
});
});
google.maps.event.addListener(country, 'click', function() {
var countryName = this.name;
var code = convert(countryName); // Calls a function that converts the name of the country to its official ISO 3166-1 alpha-2 code.
var modal = document.querySelector('.modal');
var instance = M.Modal.init(modal);
instance.open();
});
country.setMap(map);
}
}
If read in the documentation that changing the zIndex won't work because "Markers are always displayed in front of line-strings and polygons."
Is there a way to click on a polygon behind a datalayer?
EDIT
I tried to give the polygon a higher zIndex and I made the datalayer not clickable
map.data.loadGeoJson('./data/test.json');
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0,
clickAble: false,
zIndex: 50
}
})
});
function eqfeed_callback(data) {
map.data.addGeoJson(data);
}
function drawMap(data) {
var rows = data['rows'];
for (var i in rows) {
if (rows[i][0] != 'Antarctica') {
var newCoordinates = [];
var geometries = rows[i][1]['geometries'];
if (geometries) {
for (var j in geometries) {
newCoordinates.push(constructNewCoordinates(geometries[j]));
}
} else {
newCoordinates = constructNewCoordinates(rows[i][1]['geometry']);
}
var country = new google.maps.Polygon({
paths: newCoordinates,
strokeColor: 'transparent',
strokeOpacity: 1,
strokeWeight: 0.3,
fillColor: '#cd0000',
fillOpacity: 0,
name: rows[i][0],
zIndex: 100
});
google.maps.event.addListener(country, 'mouseover', function() {
this.setOptions({
fillOpacity: 0.3
});
});
google.maps.event.addListener(country, 'mouseout', function() {
this.setOptions({
fillOpacity: 0
});
});
google.maps.event.addListener(country, 'click', function() {
var countryName = this.name;
var code = convert(countryName); // Calls a function that converts the name of the country to its official ISO 3166-1 alpha-2 code.
var modal = document.querySelector('.modal');
var instance = M.Modal.init(modal);
instance.open();
});
country.setMap(map);
}
}
//console.log(map);
//test(map)
}
EDIT
Apparently the datalayer wasn't the problem, but the icon was. That is why it didn't work when I did this:
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0,
clickable: false
}
})
});
The correct way to do it is this:
map.data.setStyle(function(feature) {
var percentage = parseFloat(feature.getProperty('percentage'));
return ({
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: percentage,
fillColor: '#00ff00',
fillOpacity: 0.35,
strokeWeight: 0
},
clickable: false
})
});
You basically have 2 options here:
Set the zIndex of your Polygons to a higher number than the data layer. Your Polygons will be clickable but obviously will appear above the data layer, which might not be what you want.
Set the clickable property of the data layer to false so that you can click elements that are below. This will work if you don't need to react to clicks on the data layer...
Option 2 example code:
map.data.setStyle({
clickable: false
});
Edit: Full working example below, using option 2. As you can see the Polygon is below the data layer but you can still click it.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: -28,
lng: 137
}
});
var polygon = new google.maps.Polygon({
strokeOpacity: 0,
strokeWeight: 0,
fillColor: '#00FF00',
fillOpacity: .6,
paths: [
new google.maps.LatLng(-26, 139),
new google.maps.LatLng(-23, 130),
new google.maps.LatLng(-35, 130),
new google.maps.LatLng(-26, 139)
],
map: map
});
polygon.addListener('click', function() {
console.log('clicked on polygon');
});
// Load GeoJSON
map.data.loadGeoJson('https://storage.googleapis.com/mapsdevsite/json/google.json');
// Set style
map.data.setStyle({
fillColor: '#fff',
fillOpacity: 1,
clickable: false
});
}
#map {
height: 200px;
}
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>
<div id="map"></div>
I have found that after, setting the z-order, the maps api does not reliably send clicks to polygon feature in the top layer when there are many polygons.
I had one data layer of regions where each feature is a precinct boundary. When you click on one feature, it loads another data layer on top. The top layer consists of polygons inside the region with a higher z-order, representing house title boundaries within that region.
After the houses are loaded, clicking on a house should send the click to the house polygon, not the region. But this sometimes failed - especially if there are many houses.
To resolve the issue, after clicking on a region feature, I set that feature to be non clickable. Then the clicks always propagate to the correct house feature. You can still click on other features of the lower layer, just not the selected one. This solution should work if your data and presentation follows a similar pattern.
/* private utility is only called by this.hideOnlyMatchingFeaturesFromLayer() */
_overrideStyleOnFeature(feature, layer, key, value, overrideStyle, defaultStyle) {
if (feature.getProperty(key) === value) {
if (this.map) {
layer.overrideStyle(feature, overrideStyle);
}
} else {
if (this.map) {
layer.overrideStyle(feature, defaultStyle);
}
}
}
/* Apply an overrideStyle style to features in a data layer that match key==value
* All non-matching features will have the default style applied.
* Otherwise all features except the matching feature is hidden!
* Examples:
* overrideStyle = { clickable: false,strokeWeight: 3}
* defaultStyle = { clickable: true,strokeWeight: 1}
*/
overrideStyleOnMatchingFeaturesInLayer(layer, key, value, overrideStyle, defaultStyle) {
layer.forEach((feature) => {
if (Array.isArray(feature)) {
feature.forEach((f) => {
_overrideStyleOnFeature(f, layer, key, value, overrideStyle, defaultStyle);
});
} else {
_overrideStyleOnFeature(feature, layer, key, value, overrideStyle, defaultStyle);
}
});
}
/* example usage */
overrideStyleOnMatchingFeaturesInLayer(
theRegionsDataLayer,
'PROP_NAME',
propValue,
{ clickable: false, strokeWeight: 3},
{ clickable: true, strokeWeight: 1}
);

How to place multiple markers and draw route in google map api

I have lat, lng json in one variable
var path = [{"lat":"12.9247903824","lng":"77.5806503296"},{"lat":"10.9974470139","lng":"76.9459457397"}]
and I have created path from the lat lng values
var marker = new google.maps.Marker({
position: pos,
map: map
});
var flightPath = new google.maps.Polyline({
path: path,
geodesic: true,
strokeColor: '#ff0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map: map,
bounds: map.getBounds()
});
It is created path from the points. But Only one marker is showing. For that marker have to be shown in all points(path).
and one more, I want to get the address of all lat,lng values
you have to cast your points to google.maps.latLng Points:
var pointsPath = [new google.maps.LatLng(12.9247903824,77.5806503296),new google.maps.LatLng(10.9974470139,76.9459457397)];
Then initialize the map like this:
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(0, -180),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
var flightPath = new google.maps.Polyline({
path: pointsPath,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
Hope It helps

building multiple polygons by function in google maps javascript

I want to build a lot of areas in google maps, and have each defined with a polygon.
If I do it one by one it works without a problem (inside the initialize func):
name = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
fillOpacity: 0.05
});
//some event
//highlights polygon when mouseover
google.maps.event.addListener(name, 'mouseover', function () {
name.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
//then displaying it on the map:
name.setMap(map);
Now I want to have a function to just put in the coords to build the polygons, something like this. But just calling the function stops other polygons from being rendered, so I know there is a problem calling it:
iName = new drawPolygon(polyName, coords);
iName.setMap(map);
The function looks like this:
function drawPolygon(polyName, coords) {
polyName = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
//fillColor: 'green',
fillOpacity: 0.05
});
//highlights polygon when mouseover
google.maps.event.addListener(polyName, 'mouseover', function () {
polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
}
any help as to why, how am I calling it wrong?
drawPolygon doesn't have a return statement. It returns null. nulldoesn't have a .setMap method.
Expanding on geocodezip's answer, just add a return statement to your function.
function drawPolygon(polyName, coords) {
polyName = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
fillOpacity: 0.05
});
//highlights polygon when mouseover
google.maps.event.addListener(polyName, 'mouseover', function () {
polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
return polyName;
}
I'd also be inclined to in that case not bother passing polyName into the function as an argument. You don't bother showing us the code where you create the polyName variable prior to calling drawPolygon. But I assume you're not doing anything particularly clever with it that would require you to do so.
So refactored:
iName = new drawPolygon(coords);
iName.setMap(map);
function drawPolygon(coords) {
var polyName = new google.maps.Polygon({
paths: coords,
strokeColor: 'darkgreen',
strokeOpacity: 0.3,
strokeWeight: 1,
fillOpacity: 0.05
});
//highlights polygon when mouseover
google.maps.event.addListener(polyName, 'mouseover', function () {
polyName.setOptions({ fillColor: 'yellow', fillOpacity: 0.25 });
});
return polyName;
}

Access array inside of array in javascript for google maps api

I'm trying to access an array inside of an array in order to combine coordinates with a marker for google maps.
The path() function expects an array of google.maps.LatLng(lat,lng) to draw a polyline. The google.maps.Marker object(?) expects coordinates, some other stuff, and a text string as title. My idea now was to have a two dimensional array containing the coordinates and the title string. However, I can't make the path function accept the coordinates from my two dimensional array.
var destinations = [
[new google.maps.LatLng(52.238942,7.349558),'Somewhere'],
[new google.maps.LatLng(25.073858,55.2298444), 'Dubai'],
[new google.maps.LatLng(13.7246005,100.6331108), 'Bangkok'],
];
var flightPath = new google.maps.Polyline({
path: destinations[0],
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
Thanks a lot,
Klayman
instead of using LatLng constructors, you can pass that polyline an array of LatLngLiterals, which can have extra keys at will.
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 3,
center: {lat: 20, lng: 63}
});
var destinations = [
{lat:52.238942, lng:7.349558, title:'Somewhere'},
{lat:25.073858, lng:55.2298444, title: 'Dubai'},
{lat:13.7246005,lng:100.6331108, title: 'Bangkok'},
];
var flightPath = new google.maps.Polyline({
path: destinations,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2,
map:map
});
By the way, you were passing the first destination as path, but instead you should pass the whole collection (a polyline needs an array of vertexes). Second, your polyline was missing the map parameter for it to be drawn on the map.

Categories

Resources