How to show circle on Google Maps? - javascript

I know that this question is asked frequently, but I have a problem to show circles on my Google Map.
Actually, I get markers on my maps.
import htmlTemplate from './activityDetails.html';
export default {
template: htmlTemplate,
require: {
parent: '^main'
},
bindings: {
activity: '<'
},
controller: function controller(MapsService, GeolocationService, NgMap, $log) {
'ngInject';
this.$onInit = () => {
// Load Google Maps API script
MapsService.loadGoogleApi().then(() => {
this.loaded = true;
NgMap.getMap().then((map) => {
this.map = map;
$log.info('activityDetails component init');
this.activity.lat = this.activity.location.coordinates[0];
this.activity.lng = this.activity.location.coordinates[1];
// Save each marker in its user object to facilitate hover
this.createMarkers();
// Set geolocation notification hook
this.setGeolocationHook();
});
});
};
}
};
<div class="block-map col m6">
<ng-map class="map" center="{{$ctrl.activity.lat}}, {{$ctrl.activity.lng}}" zoom="16">
<marker position="{{$ctrl.activity.lat}}, {{$ctrl.activity.lng}}"></marker>
</ng-map>
</div>
My question is:
How to replace my markers by circles?
Thanks a lot !

You can add "Circles" to your map as described in the official API documentation.
https://developers.google.com/maps/documentation/javascript/examples/circle-simple
Important is this part:
var cityCircle = new google.maps.Circle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35,
map: map,
center: citymap[city].center,
radius: Math.sqrt(citymap[city].population) * 100
});
It's pretty straight forward.
Instead of citymap[city].center you need to pass your lat/lang object, for example {lat: 41.878, lng: -87.629}.
For the radius you can pass any number value. In the maps demo they used the population.
For NG-Map:
<shape name="circle" ng-repeat="circle in vm.circles" no-watcher="true"
stroke-color="#FF0000"
stroke-opacity="0.8"
stroke-weight="2"
fill-color="#FF0000"
fill-opacity="0.35"
center="{{circle.position}}"
radius="{{circle.radius}}">
</shape>

Related

Adding Marker to Google Maps in google-map-react with functional components

I am using the google-map-react NPM package to create a Google Map and several markers.
The information for the coordinates, infowindow, icon, etc. will come from a JSON file.
I have added onGoogleApiLoaded and yesIWantToUseGoogleMapApiInternals.
This is what my code currently looks like, with the markers being inside this file for the time being
import React, { useEffect } from 'react'
import GoogleMapReact from 'google-map-react'
let mapOptions = {
center: { lat: 39.56939, lng: -40.0000 },
zoom: 3.5,
disableDefaultUI: true,
gestureHandling: 'none',
zoomControl: false,
scaleControl: false,
zoomControlOptions: false,
scrollwheel: false,
panControl: false,
};
function ModelsMap({ data, state }) {
console.log(data.models)
function initMap() {
let markers = [
/.../
];
function Marker(props) {
let marker = new google.maps.marker({
position: props.coords,
content: props.content,
icon: props.icon,
map: map
});
let infoWindow = new google.maps.InfoWindow({
content: props.content
});
Marker.addListener('click', function () {
infoWindow.open(map, marker);
})
}
}
// useEffect(initMap, []); it will only render once
return (
<div style={{height: '100vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "YOUR_API_KEY" }}
defaultCenter={{lat: 39.56939, lng: -40.0000 }}
defaultZoom={3.5}
options={mapOptions}
yesIWantToUseGoogleMapApiInternals
onGoogleApiLoaded={({ map, maps }) => ModelsMap(map, maps)}
>
</GoogleMapReact>
</div>
);
}
export default ModelsMap;
I have followed the solution listed on This other stack overflow post, but that didn't work either.
Base on the answers on the StackOverflow you provided they uses new maps.Marker() to create a new Google Maps marker. If you want to get the value of your coordinates,icons and different properties of marker from a json data, you need to put this new maps.Marker() to loop through each json data. Below should be the value of your ModelsMap. Don't for get to import your json file.
const ModelsMap = (map, maps) => {
//instantiate array that will hold your Json Data
let dataArray = [];
//push your Json Data in the array
{
data.map((markerJson) => dataArray.push(markerJson));
}
//Loop through the dataArray to create a marker per data using the coordinates in the json
for (let i = 0; i < dataArray.length; i++) {
let marker = new maps.Marker({
position: { lat: dataArray[i].lat, lng: dataArray[i].lng },
map,
label: dataArray[i].id,
});
}
};
Here is a sample code that shows this. Please use your own API key for this to work.
Side Note: I removed the API Key in your question. Please don't share your API keys in public sites in the future.
enable javascript map api from your google cloud console

How to apply JSON responseText to Google Maps in Ruby on Rails?

So in my Rails app I am building out a region show page with multiple locations. Users are able to insert new locations and map markers need to be dynamically placed based on the latitude and longitude that they enter. In my Region show page I have the following:
<div class="container-fluid">
<div class="row">
<div class="banner" id="region-banner" data-region-name="<%=#region.name.downcase%>">
<script>document.addEventListener('DOMContentLoaded',app.regions);</script>
Then in my region.js file I have the following:
import { tns } from 'tiny-slider/src/tiny-slider.module';
import { mapStyle } from './styles/mapStyle';
app.regions = () => {
function init() {
startGoogleMap();
}
let startGoogleMap = () => {
let map = new google.maps.Map(document.getElementById('region-banner'), {
zoom: 3,
minZoom: 3,
disableDefaultUI: true,
gestureHandling: 'cooperative',
styles: mapStyle
});
var mapElement = document.getElementById('region-banner');
const regionName = mapElement.getAttribute('data-region-name');
let bounds = new google.maps.LatLngBounds();
let promise = $.getJSON('/locations.json');
promise.done(function(data) {
return $.each(data, function() {
return new google.maps.Marker({
position: {
lat: parseFloat(data.lat),
lng: parseFloat(data.lng) },
map: map,
icon: "/marker.png"
});
});
});
console.log(promise);
map.fitBounds(bounds);
};
return init();
};
Then in my controller I have:
def show
#locations = Location.all
respond_to do |format|
format.json { render json: #locations }
format.html
end
end
So no real errors are applying however...nothing appears. The console shows the responseText:“[{“id”: 5, “name”: “Chicago”, “abbreviation”: “CHI”, “lat”: “44.222”, “lng”: “-22.111”}, {“id”: 6, “name”: “Frankfort”, “abbreviation”: “FKT”, “lat”: “41.3232”, “lng”: “-19.5221”} ]”. Which really on this page I should only need/use the first.
Shouldn't it also be applying the markers at this stage since I put in the position?
this is the code responsible for setting your Markers.
I would focus on understanding why promise.done() does not run create the new google.maps.Marker() for each row in your (data) from your response.
Maybe the problem is connected to the /marker.png
promise.done(function(data) {
return $.each(data, function() {
return new google.maps.Marker({
position: {
lat: parseFloat(data.lat),
lng: parseFloat(data.lng) },
map: map,
icon: "/marker.png"
});
});
});

Hide full screen control of google map charts

Hello I am using google map charts available in google visualization chartsGoogle Map Chart. But there is no way we can hide the full screen control symbol appears in top-right position. Available options can be seen here. I have also tried to use fullscreenControl: false option given on official google map api documentation fullscreenControl but that did not work for me. Please suggest how to disable this options on mobile/ionic apps.
this.element = this.el.nativeElement;
let mapOptions = {
showTooltip: true,
tooltip: { isHtml: true },
mapType: 'satellite',
useMapTypeControl: true,
fullscreenControl: false
};
let data = [
['Lat', 'Long', 'Name'],
[37.4232, -122.0853, 'Work'],
[37.4289, -122.1697, 'University'],
[37.6153, -122.3900, 'Airport'],
[37.4422, -122.1731, 'Shopping']
];
dataTable = google.visualization.arrayToDataTable( data );
this.map = new google.visualization.Map(this.element);
this.map.draw( dataTable, mapOptions );
Thanks in advance
Below code working for me in Ionic app, You can try this:
declare var google; // declare this var above #Component({}) with your other imports
directionsDisplay = new google.maps.DirectionsRenderer;
#ViewChild('map') mapElement: ElementRef;
map: any;
this.map = new google.maps.Map(this.mapElement.nativeElement, {
zoom: 15,
center: this.maplocation, // this.maplocation={lat:'',long:''} is my Lat,Long values
fullscreenControl: false
});
this.directionsDisplay.setMap(this.map);
new google.maps.Marker({
position: this.maplocation,
map: this.map
});
In HTML :
<ion-content>
<div #map id="map"></div>
</ion-content>

google maps v3 API mouseover with GeoJson polygon layer

How to get the mouseover event to work with google maps Api V3 on Polygon shapes ?
I cannot get the event to fire on mouseover.
var data_layer25 = new google.maps.Data({ map: map });
data_layer25.loadGeoJson('http://example.com/Assets/GeoJson/USA-MO.GeoJson');
data_layer25.setStyle({
fillColor: ' #808000 ',
strokeWeight: 1
});
google.maps.event.addListener((data_layer25), "click", function () { window.location = "/RepTerritory/index/9" });
google.maps.event.addListener((data_layer25), "mouseover", function () {
this.setOptions({ fillColor: "#00FF00" });
});
google.maps.event.addListener((data_layer25), "mouseout", function () {
this.setOptions({ fillColor: "#FF0000" });
});
data_layer25.setMap(map);
Try to use this to change the style of Data Layers on mouse events:
data_layer25.addListener('mouseover', function(e) {
data_layer25.setStyle({
fillColor: "#00FF00"
});
});
data_layer25.addListener('mouseout', function(e) {
data_layer25.setStyle({
fillColor: "#FF0000"
});
});

Angular google maps: put image in Info window

I use google maps api angular (https://angular-ui.github.io/angular-google-maps/#!/api/windows) to display a map with a mark on it. The marked point, has its label with a few paragraphs and a picture.
The content of paragraphs displayed correctly, but not the image. The url of it is correct. Can add an image?
Some code:
HTML
<ui-gmap-google-map center='datos.mapa.center' options="datos.mapa.opciones" zoom='datos.mapa.zoom'>
<ui-gmap-marker coords="datos.marker_club.coords"
options="datos.marker_club.options"
idkey="datos.marker_club.id"
click="markerClick" >
<ui-gmap-window show="datos.marker_club.show"
closeClick="markerClose(marker)" >
<div><img class="mapa_escudo" scr="{{datos.escudo}}" width="32" height="32" />{{datos.club}}<br />Sede {{datos.sede}}</div>
</ui-gmap-windows>
</ui-gmap-marker>
</ui-gmap-google-map>
JS
$scope.datos.club = 'Club';
$scope.datos.sede = 'Sede';
$scope.datos.escudo = 'http://www.server.com/image.png';
uiGmapGoogleMapApi.then(function(maps) {
$scope.datos.mapa = { center: { latitude: latitud, longitude: longitud }, zoom: zoom };
$scope.datos.mapa.opciones = { scrollwheel: true };
var icon = "http://maps.google.com/mapfiles/ms/icons/orange-dot.png";
$scope.datos.marker_club = { id: 1,
coords: { latitude: latitud, longitude: longitud},
options:{
draggable: false,
icon: new google.maps.MarkerImage(icon),
},
}; $scope.markerClick = function(marker, eventName, model) {
$scope.datos.marker_club.show = !$scope.datos.marker_club.show;
};
$scope.markerClose = function(marker) {
$scope.datos.marker.show = false;
};
Sorry, just missing "ng-src" in the definition of the image!

Categories