Ways to receive alerts when a marker enters a polygon

Looking for a way to receive notifications if my marker enters any of the polygons on the map. Having trouble implementing it correctly, here is my current code:

<!DOCTYPE html>
<html>
<head>

  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
    <script src="signin.js"> </script>
    <script src="https://www.gstatic.com/firebasejs/4.10.1/firebase.js"></script>
    <script>
        // Firebase Initialization
        var config = {
            apiKey: "AIzaSyAjp8cvAcEYCwzuCyTQORL3Z1iQPdQMg_8",
            authDomain: "just-don-t.firebaseapp.com",
            databaseURL: "https://just-don-t.firebaseio.com",
            projectId: "just-don-t",
            storageBucket: "just-don-t.appspot.com",
            messagingSenderId: "925350346315"
        };
      firebase.initializeApp(config);
    </script>

    <script src="https://cdn.pubnub.com/sdk/javascript/pubnub.4.19.0.min.js"> </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAjp8cvAcEYCwzuCyTQORL3Z1iQPdQMg_8&libraries=drawing&callback=initMap" async defer>   </script>

<header><h1><center><b>WELCOME TO THE JUST DON'T APP</b> </center></h1></header>

    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
    <style >
        html, body, #map {
            height: 100%;
            margin: 0;
            padding: 0;
        }

        body {font-family: Arial, Helvetica, sans-serif;}

           [...] Visual elements such as buttons are included here but should not impact the functionality of the app [...]

<div id="map"></div>

<script>
    var lineCoords = [];
    var pubnub = new PubNub({
        publishKey:   'pub-c-22289088-791b-4f24-900a-84dc41c860bf',
        subscribeKey: 'sub-c-e781e56c-23f5-11e8-a8f3-22fca5d72012'
    });
    window.lat = 55.845890;
    window.lng = -4.423741;
    function getLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(updatePosition);
        }
        return null;
    };
    function updatePosition(position) {
        if (position) {
            window.lat = position.coords.latitude;
            window.lng = position.coords.longitude;
        }
    }
    setInterval(function(){updatePosition(getLocation());}, 10000);
    function currentLocation() {
        return {lat:window.lat, lng:window.lng};
    };


    function initMap() {
        var map = new google.maps.Map(document.getElementById('map'), {
            center: {lat: lat, lng: lng},
            zoom: 17

        });

        var infoWindow = new google.maps.InfoWindow({
            map: map
        });
        
        // Polygon coordinates defined here ...

// Attempting to detect and notify if marker enters polygon...

Here's an example implementation I'm trying:

point = Marker;
if(google.maps.containsLocation(point, mainStreetCoords) == true) {
alert("You are at the Main street");
}

If successful, I'll provide an update. Any guidance on making this work would be appreciated.

Answer №1

As per the Google Maps API documentation, to determine if a point is inside a polygon, you can use the following code snippet:

// This example requires the Geometry library. Include the libraries=geometry
// parameter when you first load the API. For example:
// <script src=".../maps/api/js?key=YOUR_API_KEY&libraries=geometry">

google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle)

The variable initialization should look something like this:

var point = new google.maps.LatLng(x, y);

It's important to note that the variable `point` in this case is not a marker.

I have implemented your logic (with the Google Maps API I am using) by adding a click event and testing it, which works successfully.

Below is the updated code:

commercialZone.addListener('click', function(e) {
    var marker = new google.maps.Marker({
        position: e.latLng,
        map: map,
        icon: {
            path: google.maps.SymbolPath.CIRCLE,
            fillColor: "red",
            fillOpacity: .2,
            strokeColor: 'white',
            strokeWeight: .5,
            scale: 10
        }
    });

    if(google.maps.geometry.poly.containsLocation(marker.position, commercialZone) == true) {
        alert("You are at the Main street");
    }
});

If you click on the commercialZone (denoted by the blue area), the alert will be triggered.

You can further customize this functionality based on your requirements.

I hope this explanation helps you in understanding the implementation better.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the text color in a React Native TouchableHighlight component

How does TouchableHighlight change the text color when tapped? I have already configured the backgroundColor using underLayColor. Here is my updated code snippet: <TouchableHighlight style={{ borderRadius: 5}} ...

Developing a placeholder directive with AngularJS

Are you looking to create a unique element in AngularJS to facilitate nested ng-repeats? Take a look at the example below: data.test = [{h:1, d:[11,12]}, {h:2, d:[21,22]}]; ---------------------- <custom ng-repeat="a in data.test"> <h3>{{a ...

Issue with AJAX function not initiating PHP script upon subsequent button clicks

My button has the following function: $(function() { $("#submit").click(function(){ $.ajaxSetup({ cache: false }); $.ajax({ url:'crfile.php', type:'GET', }); }); }; When clicked ...

Mozilla browser experiencing issues with mouse move event functionality

Here, I have a background image on the body and with the following script, when the user moves the mouse, the image in the background also moves. body { background-image: url('../images/1.png'); background-size: 98%; background-posi ...

I am attempting to design a working Hamburger icon using HTML and CSS, but it is not collapsing as intended

I am new to Bootstrap and experimenting with it. The responsive navbar in Bootstrap is not functioning as expected on my screen. Can someone help me identify the issue and fix it? <!DOCTYPE html> <html> <head> <link rel=&q ...

Enhancing performance by implementing cache mechanism for storing search results in a table with multiple filtering options using Vue

In my current project, I am utilizing VueJS. However, the issue I am facing is not necessarily exclusive to this framework - but if there is a vue-specific solution available, that would be my preference. The task at hand involves constructing a table wit ...

Setting a timeout from the frontend in the AWS apigClient can be accomplished by adjusting the

I am currently integrating the Amazon API Client Gateway into my project and I have successfully set up all the necessary requests and responses. Now, I am trying to implement a timeout feature by adding the following code snippet: apigClient.me ...

Having trouble aligning my slider in the center

Despite trying various methods to center this slider, such as using align="center" and different margin styles on the images and slider div itself, I am still facing alignment issues. Any assistance would be greatly appreciated. This is my first time posti ...

I encountered an unexpected token error while using JavaScript syntax with objects

In my current coding project, I have encountered an issue while attempting to utilize an object from a different JavaScript file. Despite importing the necessary function from this external file, there seems to be a syntax error present. Can anyone offer ...

What's the process for assigning a webpack ChunkName in a Vue project?

I have encountered an issue with webpack Chunk. I have already installed "@babel/plugin-syntax-dynamic-import". Below is my configuration and import() code. Despite this, only the entry index.js file is being generated in the output folder. What could I be ...

The Stencil EventEmitter fails to send data to the Vue instance

Attempting to develop a custom component using Stencil with an input feature. The goal is to create a component with an input field that, upon value change, emits the input to the Vue instance and logs this event to the console (later updating the value in ...

Retrieve JSON data from a PHP script to be used in an Angular scope

I am attempting to retrieve JSON data from a PHP file to use in an Angular controller. I have used json_encode(pg_fetch_assoc($result)); within the PHP file and when I check with console.log($scope.contents); in the Angular controller, the JSON data is ret ...

Loading articles seamlessly in Yii using Ajax

I am currently working on a project where I need to display articles from databases, but every time an article is viewed, the whole page reloads. I would like to load articles without having to reload the page, and I believe this can be achieved using Ajax ...

Why is it that when accessing the property of an object within a computed object, it returns as undefined instead of the object itself? Which method would be more suitable in this

Salutations. To provide some context, my intention in posing this query is to dynamically render a child component within a form based on the selection made using the <app-selector> Vue component, as straightforward as that. To simplify matters, I ...

Uploading Files Using Ajax to a PHP Class

Having some trouble with my file upload using AJAX to post to an object-oriented PHP class. Here's the AJAX code: var handleUpload = function(event) { event.preventDefault(); event.stopPropagation(); var fileInput = document.getElement ...

Creating a JavaScript array filled with database data using PHP

Below is a snippet of PHP code used to establish a connection to a database: <?php $host = "localhost"; $user = "admin"; $password = ""; $dbname = "test"; $con = new mysqli($host, $user, $password, $dbname) or die ('Could not connect to the d ...

How come the data from the Firebase real-time database is only displaying in the console and not on the page when using Vue.js?

I am encountering an issue while trying to display a value stored in my Firebase Realtime Database using the {{ exams.name }} syntax in Vue. Although I can see the value when I console.log it, it does not render on the page. However, when I attempted the s ...

What is the reasoning behind having additional parameters right next to require('../models/owners.js')?

import('../utils/handlers.js')(database, Sequelize); The structure of using import(..something)(why?) consecutively is a bit confusing to me. Can you explain it further? ...

Obtaining HTML elements from JSON using jQuery (i.e., the opposite of serializing with Ajax)

I am looking to extract values from a set of controls (INPUT, SELECT, TEXTAREA) within a DIV and send them as JSON via Ajax to a server. Utilizing jQuery's serializeArray makes this process easy. After sending the JSON data, I expect the server to re ...

Struggling to keep my image buttons aligned in a horizontal line at the center, but they keep stacking vertically instead

I'm struggling to keep a row of image buttons centered horizontally, regardless of the window size. However, when I manage to center the buttons, they end up stacking vertically instead of aligning in a single line. I've experimented with differ ...