As title, I save a lot of coordinates in database, and I will get it when I click a button. I can display all markers when I click the button, but I can't draw a polyline with these markers.
Here is my code:
<div ng-app="AAA" ng-controller="Controller">
<button ng-click="SendGetPath()">Get</button>
<div class="maps">
<!-- Add directive code (gmap directive) for show map and markers-->
<ui-gmap-google-map center="map.center" zoom="map.zoom">
<ui-gmap-marker ng-repeat="marker in markers" coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id">
<ui-gmap-window options="windowOptions" show="windowOptions.show">
<div style="max-width:200px">
<div class="header"><strong>{{marker.time}}</strong></div>
</div>
</ui-gmap-window>
</ui-gmap-marker>
<ui-gmap-polyline path="map.polyline.path" stroke="map.polyline.stroke" visible='map.polyline.visible' geodesic='map.polyline.geodesic' fit="false"></ui-gmap-polyline>
</ui-gmap-google-map>
</ui-gmap-google-map>
</div>
And in javascript,
var app = angular.module('AAA', ['uiGmapgoogle-maps']);
app.controller('Controller', function ($scope, $http) {
//this is for default map focus when load first time
$scope.map = { center: { latitude: 22.25, longitude: 114.1667 }, zoom: 14, mapTypeId: google.maps.MapTypeId.ROADMAP }
$scope.carlist = [];
$scope.locations = [];
var id = 1;
//Send command to device
$scope.SendGetPath = function () {
$http.get('GetPath', {
params: {
regno: document.getElementById('car').value,
date: document.getElementById('date').value
}
}).then(function (data) {
//alert("Sent");
$scope.locations = data.data;
$scope.markers = [];
angular.forEach($scope.locations, function (value, key) {
$scope.markers.push({
id: id,
coords: { latitude: value.Latitude, longitude: value.Longitude },
//title: value.RegNo,
//battery: value.Battery
//address: data.data.Address,
//image : data.data.ImagePath
time: value.Time
});
id=id+1;
});
$scope.map = { center: { latitude: 22.25, longitude: 114.1667 }, zoom: 12 }
}, function () {
//alert('Load Error');
});
}
});
And how do I add arrow to the path of the map?
Related
I'm trying to implement a map with a route that has a waypoint and a dynamic origin within a Google Site. I'd like to set the origin based on the user's location who access the Google Sites and I'm using the HTML5 Geolocation API to retrieve the user's geolocation. However, I'm not able to retrieve properly the user's geolocation.
Here you will find the code I'm currently implementing.
<!DOCTYPE html>
<html>
<head>
<title>PATH A</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<style type="text/css">
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: 37.132, lng: 13.869 },
});
directionsRenderer.setMap(map);
const onChangeHandler = function () {
calculateAndDisplayRoute(directionsService, directionsRenderer);
};
window.onload = onChangeHandler;
}
function setPosition(position){
currentOrigin = {};
currentOrigin.lat = position.coords.latitude;
currentOrigin.lng = position.coord.longitude;
}
function calculateAndDisplayRoute(directionsService, directionsRenderer){
let currentOrigin = new google.maps.LatLng(37.081, 14.214);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setPosition);
} else {
// Browser doesn't support Geolocation
console.log("Browser does not support geolocation");
}
const waypts = [];
waypts.push({
location: { lat: 37.261, lng: 13.588},
stopover: true
});
directionsService.route({
origin: currentOrigin,
destination: {
lat: 37.314 , lng: 13.576
},
optimizeWaypoints: false,
waypoints: waypts,
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if(status === "OK" && response) {
directionsRenderer.setDirections(response);
} else {
console.log("An error occurred: " + status);
}
});
}
</script>
</head>
<body>
<div id="map"></div>
<!-- Async script executes immediately and must be after any DOM elements used in callback. -->
<script
src="https://maps.googleapis.com/maps/api/js?key=*********&callback=initMap&libraries=&v=weekly"
async
></script>
</body>
</html>
Is the Geolocation API somehow blocked by the Google Sites' policies? If so, is there any other way to set up a dynamic origin? The desired solution is to have a map on the site that has a route with a specific waypoint.
Thanks in advance for your attention.
So a couple of things first I think you have a typo in your setPosition callback function the longitude should be position.coords.longitude . Also you need to set the center of the google maps object when the navigator returns a lat and lng. Right now currentOrigin is out of scope of the map and never is able to update. One thing you could possibly try is passing a reference of your map object to calculateAndDisplayRoute and setting the map's location in the setPosition callback.
Try this:
function initMap() {
const directionsService = new google.maps.DirectionsService();
const directionsRenderer = new google.maps.DirectionsRenderer();
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 8,
center: { lat: 37.132, lng: 13.869 },
});
directionsRenderer.setMap(map);
const onChangeHandler = function () {
calculateAndDisplayRoute(directionsService, directionsRenderer, map);
};
window.onload = onChangeHandler;
}
function setPosition(position, map){
currentOrigin = {};
map.setCenter({ lat : position.coords.latitude, lng: position.coords.longitude });
}
function calculateAndDisplayRoute(directionsService, directionsRenderer, map){
let currentOrigin = new google.maps.LatLng(37.081, 14.214);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
setPosition(position, map);
});
} else {
// Browser doesn't support Geolocation
console.log("Browser does not support geolocation");
}
const waypts = [];
waypts.push({
location: { lat: 37.261, lng: 13.588},
stopover: true
});
directionsService.route({
origin: currentOrigin,
destination: {
lat: 37.314 , lng: 13.576
},
optimizeWaypoints: false,
waypoints: waypts,
travelMode: google.maps.TravelMode.DRIVING
}, (response, status) => {
if(status === "OK" && response) {
directionsRenderer.setDirections(response);
} else {
console.log("An error occurred: " + status);
}
});
}
I passed the map object through to the callback so that setCenter could be called on the navigators position.
I have created the following code based on the tutorial :http://webdesignerwall.com/tutorials/interactive-world-javascript-map.
This is the link to the source code of html file https://gist.github.com/anonymous/84795387d09fe08ee8b6
I have alterate it to display radomly one dot at the time on the map. But what I want to do is to have the dots displayed with a "pulse" effect. Originally the dots are displayed in the correct location, but when I added the following to class to activate the pulse effect the location of the circles changed...I've tried to change the scale but still does not work.. when I removed the scale then it stopped "pulsing". Do you have any ideas on the matter?
$( document ).ready(function() {
//Load the map after the page loads
if (window.addEventListener){ // W3C standard
window.addEventListener('load', function(){worldmap()}, false); //true means that this request will be ignored if auto is set to off
}
else if (window.attachEvent){ // Microsoft
window.attachEvent('onload', function(){worldmap()});
}
function worldmap(){
image_array=[];
var div = document.getElementById('map');
var width=div.offsetWidth;
var scale=width/887;
var height=width*.62;
var paper = Raphael(div, width, height); //create the Raphael canvas in the map div
var background=paper.rect(0, 0, width, height); //create the background
background.attr({fill: ' rgba(32, 32, 32, 1)', 'stroke-width': 0});
//create the map
var map_path="m 267.53333,537.24584 c -0.6,-0.6 -1,...couldn't put the whole path due to charecter limitation";
var map=paper.path(map_path).attr({fill: '#483D8B', stroke: 'white'}).scale(scale, scale, 0, 0);
//create set of locations
var location_set=paper.set();
//create locations
for (var location in locations){
var loc=locations[location];
var xy=get_xy(loc.lat, loc.lng);
var loc_obj=paper.circle(xy.x, xy.y, 7).attr({fill: loc.color, stroke: 'white', 'stroke-width': 2, }).scale(scale, scale, 0, 0);
loc_obj.node.setAttribute("id","i"+location)
loc_obj.node.setAttribute("class","loader")
loc_obj.hide();
loc_obj.name=loc.name;
loc_obj.x=xy.x;
loc_obj.y=xy.y;
location_set.push(loc_obj);
}
var name = document.getElementById('location_name');
// *********************************************Functions *********************************************
function get_xy(lat, lng){ //http://stackoverflow.com/questions/14329691/covert-latitude-longitude-point-to-a-pixels-x-y-on-mercator-projection
var mapWidth=2058;
var mapHeight=1746;
var factor=.404;
var x_adj=-391;
var y_adj=37;
// get x value
var x = (mapWidth*(180+lng)/360)%mapWidth+(mapWidth/2);
//convert from degrees to radians
var latRad = lat*Math.PI/180;
// get y value
var mercN = Math.log(Math.tan((Math.PI/4)+(latRad/2)));
var y = (mapHeight/2)-(mapWidth*mercN/(2*Math.PI));
return { x: x*factor+x_adj, y: y*factor+y_adj}
}
function GetLocationsLength(location){
function ObjectLength( location ) {
var length = 0;
for( var key in location ) {
if( location.hasOwnProperty(key) ) {
++length;
}
}
return length;
};
l=ObjectLength( location );
RandomGenerator(l,locations,location_set);
} //end of selfinvoked Random_Generator
GetLocationsLength(locations)
function RandomGenerator(length,locations,location_set){
location_set[0].show(); //console.log(innerHtml);
var counter=0;
var x=0;
previousX=-1;
var refreshId = setInterval( function() {
x = Math.floor((Math.random() * location_set.length) ); //generates a random number between 0-4
if(counter==0)
{location_set[0].show();
previousX=0;
}
counter++;
location_set[previousX].hide();
location_set[x].show();
//add elements to the box
// var flag = locations[x].name.toString();
//$("img#location").attr("src", flag);
$("img#location").css({"width": "40px", "height": "20px"});
$("span#name").text( locations[x].name).show('slow');
var link = locations[x].name.toString();
$("a#instituteLink").attr("href", link);
$("span#instituteLink").text( locations[x].name).show('slow');
previousX=x;
}, 6000); //end of refreshid funvtion
}//end of function RandomGenerator
}// end of world map function
// *********************************************Location Data*********************************************
var locations={
0: {
name: 'Paris',
lat: 48.866666670,
lng: 2.333333333,
color: 'violet',
},
1: {
name: 'Shanghai',
lat: 31.10,
lng: 121.366,
color: 'black',
},
2: {
name: 'New York',
lat: 40.7,
lng: -73.90,
color: 'red',
},
3: {
name: 'Los Angeles',
lat: 34.0,
lng: -118.25,
color: 'purple',
},
4: {
name: 'Cape Town',
lat: -35.916,
lng: 18.36,
color: 'hotpink',
},
5: {
name: 'Santiago',
lat: -33.45,
lng: -70.66,
color: 'blue',
},
6: {
name: 'Cairo',
lat: 30.05,
lng: 31.25,
color: 'green',
},
7: {
name: 'yolo',
lat: 40.05,
lng: 11.25,
color: 'green',
},
8: {
name: 'Singapore',
lat: 1.30,
lng: 103.83,
color: 'orange',
}
}
});
I have working java script Google Map Api v3 with Geocoding.
When I type for example post code in search box I can select address from list. If I will do same thing and press ENTER nothing is happening. How to modify code?
<input id="address" type="textbox">
Java script code:
var geocoder;
var map;
var marker;
function initialize(){
//MAP
var latlng = new google.maps.LatLng(51.469186, -0.361166);
var options = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//GEOCODER
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: false
});
//CIRCLE
var circle = new google.maps.Circle({
map: map,
center: new google.maps.LatLng(51.469186, -0.361166),
fillColor: '#204617',
fillOpacity: 0.2,
strokeColor: '#6DE953',
strokeOpacity: 0.4,
strokeWeight: 2
});
circle.setRadius(10000);
}
$(document).ready(function() {
initialize();
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
document.getElementById("address").focus();
});
});
I have try adding search button:
<input id="search" type="button" value="Search" onclick="codeAddress()">
and adding function codeAddress() to Java Script but I must have done something wrong as that didn't worked.
Working (without ENTER) jsfiddle
you can try this maybe you'll get some ideas. https://developers.google.com/maps/documentation/javascript/examples/places-autocomplete-addressform
they are also using geocode, so you can refer the code.
I'm not a 100% certain what you are doing wrong, since you did not post all the code. But this example works (I tested in FF):
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script> <!-- Google Maps API -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
var geocoder;
var map;
var marker;
function initialize(){
//MAP
var latlng = new google.maps.LatLng(51.469186, -0.361166);
var options = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//GEOCODER
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: false
});
//CIRCLE
var circle = new google.maps.Circle({
map: map,
center: new google.maps.LatLng(51.469186, -0.361166),
fillColor: '#204617',
fillOpacity: 0.2,
strokeColor: '#6DE953',
strokeOpacity: 0.4,
strokeWeight: 2
});
circle.setRadius(10000);
}
</script>
<script>
$(document).ready(function() {
initialize();
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setCenter(location);
}
});
document.getElementById("address").focus();
});
});
</script>
<style>
/* style settings for Google map */
#map_canvas
{
width : 500px; /* map width */
height: 500px; /* map height */
}
</style>
</head>
<body onload="initialize()">
<!-- Dislay Google map here -->
<div id='map_canvas' ></div>
<input id="address" type="textbox">
</body>
</html>
I am using gmaps3 to show an overlay on mouseover but the mouseover listener is not called when I move my mouse to the marker
Following is the entire code
function init_map(){
$mapElements=jQuery(".map-details");
var markers=[];
$mapElements.each(function(e){
$e=$(this);
if(!($e.data("lat")&&$e.data("long")))
return;
var img_p="https://encrypted.google.com/images/srpr/logo4w.png"
var marker= {
latLng:[$e.data("lat"),$e.data("long")],
data:{
img_preview: img_p,
properties_name:"023 Central Park [Rent]",
properties_desc:"Lorem Ipsum Go Green",
properties_link:"#",
zip:001233,
city:"Jakarta"
}
}
markers.push(marker);
});
<?php /* if($first):/**/?>
$("#map-canvas-multiple").gmap3({
map:{
// CENTRAL MAP DEFAULT
address:"New Delhi, India",
options:{
zoom:8,
scaleControl: false,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
}
},
marker:{
// DATA LOCATION
values:markers
},
events:{
mouseover: function(marker, event, context){
console.log("hello from mouseover");
$(this).gmap3(
{
clear:"overlay"
},
{
overlay:{
latLng: marker.getPosition(),
options:{
content: "<div class='info-location'>" +
"<div class='text'><h4>"
+ context.data.properties_name +
"</h4>"+
"<img src='"+ context.data.img_preview +"' width=90> $300.999 <br/>"+
context.data.properties_desc +
"<br/><a href='"+context.data.properties_link +"'class='btn btn-proper btn-small'>See Detail</a></div>" +
"</div>" +
"<div class='arrow-location'></div>",
offset: {
x:-46,
y:-73
}
}
}
});
}
}
});
}
$(document).ready(init_map);
The markers get shown but mousover on them doesn't work
No errors in console. The hello mouseover line is not printed to console either
Figured this out after many hours of brainstorming. The events object goes inside the markers object
Instead of
marker:{
// DATA LOCATION
values:markers
},
events:{
mouseover: function(marker, event, context){
console.log("hello from mouseover");
$(this).gmap3(
{
clear:"overlay"
},
it should be
marker:{
// DATA LOCATION
values:markers,
events:{
mouseover: function(marker, event, context){
console.log("hello from mouseover");
$(this).gmap3(
{
clear:"overlay"
},
},
To initialize google.maps as an AMD module, compliant with twitter/flight and requirejs, use:
define([
'components/flight/lib/component',
'async!http://maps.google.com/maps/api/js?key=AIzaSyDp9D9Db1CWfeGUJ1bin45s2WKZN5sapuM&sensor=false'
], function(defineComponent){
return defineComponent(newMap);
function newMap () {
this.defaultAttrs({
// Selector
mapDiv: '#map',
// Map Canvas
mapCanvas: {},
// Initialized?
initializedMap: false
});
this.initializeMap = function () {
var mapCenter = new google.maps.LatLng(39.960664,-75.605488);
var mapOptions = {
zoom: 15,
center: mapCenter,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
this.attr.mapCanvas = new google.maps.Map(document.getElementById("map"), mapOptions);
if (this.attr.mapCanvas != {} ) {
this.attr.initializedMap = true;
this.trigger(document, 'mapInitialized', {
status: this.attr.initializedMap
});
};
// ### Map events
//-----------
// Mouse Up
google.maps.event.addListener(this.attr.mapCanvas, 'mouseup', function() {
this.trigger('mouseup');
});
// Zoom Changed
google.maps.event.addListener(this.attr.mapCanvas, 'zoom_changed', function() {
this.trigger('zoomChanged');
});
};
this.mouseup = function () {
console.log("what");
}
this.zoomChanged = function () {
console.log("is up");
}
this.after('initialize', function () {
this.on('mouseup', this.mouseup);
this.on('zoomChanged', this.zoomChanged);
this.on('initializeMap', this.initializeMap);
this.trigger('initializeMap');
});
}
});
I put together a Google Maps AMD loader plugin, which adds some functionality on top of the async! loader.
require.config({
googlemaps: {
params: {
key: 'abcd1234', // sets api key
libraries: 'geometry' // set google libraries
}
}
});
require(['googlemaps!'], function(gmaps) {
// google.maps available as gmaps
var map = new gmaps.Map('map-canvas');
});