How to use google map api in react - javascript

I want to implement below code in react. Where can I use 'script' tag and how can I draw below map. Is there any built-in Library for showing route on map
<div id="map"></div>
<script>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: 'terrain'
});
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=APIKEY&callback=initMap">
</script>

I suggest that you use the map component that is provided by primefaces primereact, it's functional and easily usable. Here is example taken from their: documentation:
import {GMap} from 'primereact/components/gmap/GMap';
onMapReady(event) {
this.setState({
overlays: [
new google.maps.Marker({position: {lat: 36.879466, lng: 30.667648}, title:"Konyaalti"}),
new google.maps.Marker({position: {lat: 36.883707, lng: 30.689216}, title:"Ataturk Park"}),
new google.maps.Circle({center: {lat: 36.90707, lng: 30.56533}, fillColor: '#1976D2', fillOpacity: 0.35, strokeWeight: 1, radius: 1500}),
new google.maps.Polyline({path: [{lat: 36.86149, lng: 30.63743},{lat: 36.86341, lng: 30.72463}], geodesic: true, strokeColor: '#FF0000', strokeOpacity: 0.5, strokeWeight: 2})
]
})
}
<GMap overlays={this.state.overlays} options={options} style={{width: '100%', minHeight: '320px'}} onMapReady={this.onMapReady}
onMapClick={this.onMapClick} onOverlayClick={this.onOverlayClick} onOverlayDragEnd={this.handleDragEnd} />

Related

Filling Google Maps polygon from array of LatLng points

I have an array of coordinates in LatLng format. I would like to construct a polygon using those coordinates. I know I can hardcode a polygon with individual coordinates like this:
var triangleCoords = [
{lat: A, lng: A},
{lat: B, lng: B},
{lat: C, lng: C}]
Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?
Correct me if I had misunderstood your question.
Q:
Is it possible to place the LatLng data points from my array into triangleCoords and create the polygon that way?
A:
Short answer: No. Unfortunately there is no smartness in the google.maps.Polygon code which would magically try to figure out the lat and lng coordinates of the specified google.maps.LatLng objects for you.
You will need to use the lat() and lng() APIs to return the raw coordinate values from the google.maps.LatLng object and plug that into your array. No shortcut.
Example:
var map = new google.maps.Map(document.getElementById("map"),
{
zoom: 4,
center: new google.maps.LatLng(22.7964, 79.8456),
mapTypeId: google.maps.MapTypeId.HYBRID
});
var coordinateA = new google.maps.LatLng(18.979026,72.949219);
var coordinateB = new google.maps.LatLng(28.613459,77.255859);
var coordinateC = new google.maps.LatLng(22.512557,88.417969);
var coordinateD = new google.maps.LatLng(12.940322,77.607422);
var coords =
[
{lat: coordinateA.lat(), lng: coordinateA.lng() },
{lat: coordinateB.lat(), lng: coordinateB.lng() },
{lat: coordinateC.lat(), lng: coordinateC.lng() },
{lat: coordinateD.lat(), lng: coordinateD.lng() }
];
metros = new google.maps.Polygon(
{
paths: coords,
strokeColor: "#0000FF",
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: "#0000FF",
fillOpacity: 0.26
});
See here for a working JSFiddle example.
http://jsfiddle.net/SamuelToh/3srggbmu/
Here same way am trying polygon google route map dynamically from mysql, it work only on marker, but its not working in polygon ,
here is the code
function initMap()
{
var map = new google.maps.Map(document.getElementById('map'),{
zoom: 5,
center: { lat: 13.36, lng: 77.03 },
});
var planCoordinates = new Array();
// var locations = [
// {lat: 13.367797388285002, lng:77.03707749682616},
// {lat:13.341074247677549, lng:77.0394807561035},
// {lat:13.379153826558369, lng: 77.08685929614256},
// {lat: 13.367797388285002, lng:77.03707749682616},
// ];
<?php
if ($result->num_rows > 0)
{
foreach($result as $key => $row)
{
?>
var locations = [{lat: <?php echo $row['lat']; ?>,lng: <?php echo $row['lng']; ?>}];
for (let i = 0; i < locations.length; i++) {
let obj = locations[i];
planCoordinates[i] = new google.maps.LatLng(obj.lat, obj.lng);
var myLatlng = new google.maps.LatLng(obj.lat, obj.lng);
poly = new google.maps.Polygon({
path: planCoordinates,
geodesic: true,
strokeColor: 'hsla(290,60%,70%,0.3)',
strokeOpacity: 1.0,
strokeWeight: 3,
fillColor: 'hsla(290,60%,70%,0.3)',
fillOpacity: 1.35
});
poly.setMap(map);
var infoWindow = new google.maps.InfoWindow({ content: contentString.this });
var marker = new google.maps.Marker({
position: myLatlng,
title: "Jumbookart",
zIndex: 999,
});
marker.setMap(map);
let ikonica = new google.maps.Marker({
position: myLatlng,
title: "Markeri",
icon: {
path: google.maps.SymbolPath.CIRCLE,
scale: 7
}
});
ikonica.setMap(map);
}
<?php } } ?>
var arrayOfFlightPlans = [locations];
//Loops through all polyline paths and draws each on the map.
for (let i = 0; i < arrayOfFlightPlans.length; i++) {
flightPath = new google.maps.Polygon({
path: arrayOfFlightPlans[i],
geodesic: true,
strokeColor: 'hsla(290,60%,70%,0.3)',
strokeOpacity: 1.0,
strokeWeight: 3,
fillColor: 'hsla(290,60%,70%,0.3)',
fillOpacity: 1.35
});
flightPath.setMap(map);
}
}

How to Plot Route on Google Maps

I am using the below code to Plot a Route
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 0, lng: -180},
mapTypeId: google.maps.MapTypeId.TERRAIN
});
var flightPlanCoordinates = [
{lat: 37.772, lng: -122.214},
{lat: 21.291, lng: -157.821},
{lat: -18.142, lng: 178.431},
{lat: -27.467, lng: 153.027}
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
geodesic: true,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 2
});
flightPath.setMap(map);
}
Using Polylines gives only Straight Lines is there any other method to Plot the Route as in the Sample Route Image.
I have tried regarding but didn't got any such method
Take a look here:http://www.geocodezip.com/v3_polyline_example_arc.html and here: http://www.geocodezip.com/v3_polyline_example_rhumb.html
To do this you probably want to abstract the path over a sinusoid of some kind to make it more curvy and visually attractive. Check out the question below, there are a lot of in-depth answers.
Curved line between two near points in google maps

Is my javascript good for google maps API?

I'm using squarespace to build my website and want to insert a custom map from google maps javascript api. I've followed tutorial from W3school and from Google's own tutorial to build my map and follow steps as below :
What I'm trying to archive is a map like this
google map example
Step 1: Insert a embed block for html
<div id= "map"></div>
Step 2: insert javascript in page header
<script
src="http://maps.google.cn/maps/api/js?key=my-key">
</script>
<script type="text/javascript">
function initMap() {
var map = new google.maps.Map(document.getElementById(‘map'), {
zoom: 12,
center: {lat: 48.877412, lng: 2.359221},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Define the LatLng coordinates for the polygon's path.
var 10th = [
{lat: 48.883863, lng: 2.349500},
{lat: 48.870752, lng: 2.347915},
{lat: 48.867593, lng: 2.363981},
{lat: 48.872958, lng: 2.377065},
{lat: 48.877800, lng: 2.370605},
{lat: 48.882765, lng: 2.370164},
{lat: 48.884218, lng: 2.368480},
{lat: 48.884670, lng: 2.360258},
{lat: 48.883863, lng: 2.349500}
];
// Construct the polygon.
var 10th = new google.maps.Polygon({
paths: triangleCoords,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
10th.setMap(map);
}
</script>
Step 3 : in custom css section
#googleMap {
width: 100%;
height: 380px;
}
But so far, I got either a blank page once javascript injected or error page (with code visible on top of the page... )
Here the link to my webpage on SquareSpace https://handa-cheng-a3wm.squarespace.com/1starrondissement
Thanks !
You have few typos in your code:
var 10th = [...] // invalid variable name
^---
Variables names in JavaScript must not begin with numbers. And you have defined the function but didn't run it.
You have not set height for #map in css.
<div id= "map"></div>
#googleMap { // <== this is not correct id as used in html above
width: 100%;
height: 380px;
}
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 48.877412, lng: 2.359221},
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Define the LatLng coordinates for the polygon's path.
var points = [
{lat: 48.883863, lng: 2.349500},
{lat: 48.870752, lng: 2.347915},
{lat: 48.867593, lng: 2.363981},
{lat: 48.872958, lng: 2.377065},
{lat: 48.877800, lng: 2.370605},
{lat: 48.882765, lng: 2.370164},
{lat: 48.884218, lng: 2.368480},
{lat: 48.884670, lng: 2.360258},
{lat: 48.883863, lng: 2.349500}
];
// Construct the polygon.
var polygon = new google.maps.Polygon({
paths: points,
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
polygon.setMap(map);
}
initMap();
#map {
height: 300px;
}
<script
src="http://maps.googleapis.com/maps/api/js">
</script>
<div id="map"></div>

Google map error - a.lng is not a function

I'm planning to use google map "containsLocation()" API in one of my application. The doc link is - https://goo.gl/4BFHCz
I'm following the same example. Here is my code.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Polygon arrays</title>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
<div id="map"></div>
<script>
// This example requires the Geometry library. Include the libraries=geometry
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
//center: {lat: 24.886, lng: -70.269},
center: {lat: 12.9629277, lng: 77.7178972},
zoom: 30,
});
/*var triangleCoords = [
{lat: 25.774, lng: -80.19},
{lat: 18.466, lng: -66.118},
{lat: 32.321, lng: -64.757}
];*/
var triangleCoords = [
{lat: 12.96301273, lng: 77.71785952},
{lat: 12.96314857, lng: 77.71784072},
{lat: 12.96316124, lng: 77.71784037},
{lat: 12.96295465, lng: 77.71788993},
{lat: 12.96293329, lng: 77.7179345},
];
var bermudaTriangle = new google.maps.Polygon({paths: triangleCoords});
google.maps.event.addListener(map, 'click', function(e) {
var curPosition = {"lat":12.9629277,"lng":77.7178972};
//var curPosition = e.latLng;
console.log("e content : "+JSON.stringify(e.latLng));
console.log("curPosition content : "+JSON.stringify(curPosition));
var resultColor =
google.maps.geometry.poly.containsLocation(curPosition, bermudaTriangle) ?
'red' :
'green';
new google.maps.Marker({
position: curPosition,
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: resultColor,
fillOpacity: .2,
strokeColor: 'white',
strokeWeight: .5,
scale: 10
}
});
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCiAur6ANJsV776iVmMDJcHYjQkXrXyu8s&libraries=geometry&callback=initMap"
async defer></script>
</body>
</html>
If you see I've created a curPosition variable which holds the latLng data. My problem at here is as long as var curPosition = e.latLng; it works fine but, the moment I changed that to var curPosition = {"lat":12.9629277,"lng":77.7178972}; it's started showing error "Uncaught TypeError: a.lng is not a function".
Can't able to understand why it's happening? Any clue...?
Console.log screen shot attached
Regards
the containsLocation method requires a google.maps.LatLng as the "point" (at least at present), you can't use a google.maps.LatLngLiteral for currentLocation.
from the documentation:
containsLocation(point:LatLng, polygon:Polygon) | Return Value: boolean
Computes whether the given point lies inside the specified polygon.
var curPosition = new google.maps.LatLng(12.9629277,77.7178972);
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 12.9629277,
lng: 77.7178972
},
zoom: 30,
});
var triangleCoords = [
{lat: 12.96301273,lng: 77.71785952}, {lat: 12.96314857, lng: 77.71784072}, {lat: 12.96316124, lng: 77.71784037}, {lat: 12.96293329, lng: 77.7179345}, {lat: 12.96295465, lng: 77.71788993}];
var bermudaTriangle = new google.maps.Polygon({
paths: triangleCoords,
map: map
});
var curPosition = new google.maps.LatLng(12.9629277, 77.7178972);
console.log("curPosition content : " + JSON.stringify(curPosition));
var resultColor =
google.maps.geometry.poly.containsLocation(curPosition, bermudaTriangle) ?
'red' :
'green';
new google.maps.Marker({
position: curPosition,
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: resultColor,
fillOpacity: .2,
strokeColor: 'white',
strokeWeight: .5,
scale: 10
}
});
var curPositionB = new google.maps.LatLng(12.963, 77.71788993);
var resultColorB = google.maps.geometry.poly.containsLocation(curPositionB, bermudaTriangle) ?
'red' :
'green';
new google.maps.Marker({
position: curPositionB,
map: map,
icon: {
path: google.maps.SymbolPath.CIRCLE,
fillColor: resultColorB,
fillOpacity: .2,
strokeColor: 'white',
strokeWeight: .5,
scale: 10
}
});
}
google.maps.event.addDomListener(window, 'load', initMap);
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?libraries=geometry&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="map"></div>

Google map longitude latitude defined twice

I want to define the longitude latitude once. Right now it only works if it's defined twice.
I've moved things around but all I've managed is a broken map. The font icon only shows when long and lat are in there twice.
Here's my code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(27.86336,-101.130738),
zoom: 16,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("google-map"), mapOptions);
new google.maps.Marker({
map: map,
icon: {
path: fontawesome.markers.EXCLAMATION,
scale: 0.5,
strokeWeight: 0,
strokeColor: 'transparent',
strokeOpacity: 0,
fillColor: 'red',
fillOpacity: 1,
},
clickable: false,
position: new google.maps.LatLng(27.86336,-101.130738)
});
}
google.maps.event.addDomListener(window, "load", initialize);
I've used the font marker solution from here: Using Icon Fonts as Markers in Google Maps V3 if that helps
You can merely do:
function initialize() {
var myLatLng = new google.maps.LatLng(27.86336. -101.130738);
var mapOptions = {
center: myLatLng,
zoom: 16,
disableDefaultUI: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("google-map"), mapOptions);
new google.maps.Marker({
map: map,
icon: {
path: fontawesome.markers.EXCLAMATION,
scale: 0.5,
strokeWeight: 0,
strokeColor: 'transparent',
strokeOpacity: 0,
fillColor: 'red',
fillOpacity: 1,
},
clickable: false,
position: myLatLng
});
}
google.maps.event.addDomListener(window, "load", initialize);
As long as you declare the variable within scope you shouldn't have any issues?

Categories